标签:
求连通分量
Sample Input
2 //T
5 3 //n m
1 2// u v
2 3
4 5
5 1
2 5
Sample Output
2
4
1 # include <iostream> 2 # include <cstdio> 3 # include <cstring> 4 # include <algorithm> 5 # include <cmath> 6 # include <queue> 7 # define LL long long 8 using namespace std ; 9 10 const int MAXN=1010; 11 int F[MAXN] ; 12 int find(int x) //找x的祖先结点 13 { 14 while(x!=F[x]) 15 x=F[x]; 16 return x; 17 } 18 void bing(int u,int v) 19 { 20 int t1=find(u); 21 int t2=find(v); 22 if(t1!=t2) //这两个点不在一个集合里 23 F[t1]=t2; //合到一个集合里 24 } 25 26 27 int main() 28 { 29 //freopen("in.txt","r",stdin) ; 30 int T ; 31 scanf("%d" , &T) ; 32 while(T--) 33 { 34 int n , m ; 35 int i ; 36 scanf("%d %d" , &n , &m) ; 37 for (i = 1 ; i<= n ; i++) 38 F[i] = i ; 39 int u , v ; 40 while(m--) 41 { 42 scanf("%d %d" , &u , &v) ; 43 bing(u,v) ; 44 } 45 int res = 0 ; 46 for (i = 1 ; i<= n ; i++) 47 if (F[i] == i) 48 res++ ; 49 printf("%d\n" , res) ; 50 51 } 52 53 return 0; 54 }
标签:
原文地址:http://www.cnblogs.com/-Buff-/p/4596378.html