题目地址
http://acm.hdu.edu.cn/showproblem.php?pid=1213
1 #include<iostream> 2 using namespace std; 3 #define MAX 100005 4 int fa[MAX]; 5 6 int findHead(int x) 7 { 8 while(x!=fa[x]) 9 x=fa[x]; 10 return x; 11 } 12 13 void Union(int x,int y) 14 { 15 int fa_x=findHead(x); 16 int fa_y=findHead(y); 17 if(fa_x!=fa_y) fa[fa_x]=fa_y; 18 } 19 20 int main() 21 { 22 int T,N,M,A,B,count; 23 cin>>T; 24 while(T--){ 25 count=0; 26 cin>>N>>M; 27 for(int j=1;j<=N;j++) fa[j]=j; 28 for(int i=0;i<M;i++){ 29 cin>>A>>B; 30 Union(A,B); 31 } 32 for(int i=1;i<=N;i++) 33 if(fa[i]==i) count++; 34 cout<<count<<endl; 35 } 36 return 0; 37 }