sdut1918
简单并查集 有联通的就合并在一起 最后看共有多少棵树 就有多少个灾民集中区域
View Code
1 #include <stdio.h> 2 #include <stdlib.h> 3 int father[201],num[201]; 4 int find(int x) 5 { 6 if(x!=father[x]) 7 { 8 father[x] = find(father[x]); 9 } 10 return father[x]; 11 } 12 void union1(int x, int y) 13 { 14 father[x] = y; 15 } 16 int main() 17 { 18 int i, j, t, n, m,f[201],a,b; 19 scanf("%d", &t); 20 while(t--) 21 { 22 int k = 0; 23 scanf("%d%d", &n, &m); 24 for(i = 1 ; i <= n ; i++) 25 { 26 father[i] = i; 27 num[i] = 1; 28 f[i] = 0; 29 } 30 for(i = 1 ; i <= m ; i++) 31 { 32 scanf("%d%d", &a,&b); 33 a = find(a); 34 b = find(b); 35 union1(a,b); 36 } 37 for(i = 1 ; i <= n ; i++) 38 { 39 f[find(i)]++; 40 } 41 for(i = 1 ; i <= n ; i++) 42 if(f[i]!=0) 43 k++; 44 printf("%d\n", k); 45 } 46 return 0; 47 }