Finding connected components
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 LLLong Long8 using namespacestd;9 Ten Const intmaxn=1010; One intF[MAXN]; A intFindintX//find the ancestor node of x - { - while(x!=F[x]) thex=F[x]; - returnx; - } - voidBingintUintv) + { - intt1=find (u); + intT2=Find (v); A if(T1!=T2)//These two points are not in a collection. atF[t1]=t2;//fit into a collection. - } - - - intMain () - { in //freopen ("In.txt", "R", stdin); - intT; toscanf"%d", &T); + while(t--) - { the intN, M; * inti; $scanf"%d%d", &n, &m);Panax Notoginseng for(i =1; i<= N; i++) -F[i] =i; the intu, v; + while(m--) A { thescanf"%d%d", &u, &v); + Bing (u,v); - } $ intres =0 ; $ for(i =1; i<= N; i++) - if(F[i] = =i) -res++ ; theprintf"%d\n", res); - Wuyi } the - return 0; Wu}
View Code
HDU 1213 to find the connected component (and find the template problem)