并查集 求总集合(结点)数:
1 #include<stdio.h> 2 #define LEN 10000 3 4 int p[LEN]; 5 6 int _find(int x) { 7 return p[x] == x ? x : (p[x] = _find(p[x])); 8 } 9 10 int main() { 11 int num, ans, i, j; 12 scanf("%d", &num); 13 while(num--){ 14 int n, m; 15 scanf("%d%d", &n, &m); 16 for(i = 1; i <= n; i++) 17 p[i] = i; 18 for(i = 0; i < m; i++){ 19 int a, b, t1, t2; 20 scanf("%d%d", &a, &b); 21 t1 = _find(a); 22 t2 = _find(b); 23 if(t1 != t2) 24 p[t1] = t2; 25 } 26 ans = 0; 27 for(i = 1; i <= n; i++) 28 if(i == p[i]) 29 ans++; 30 printf("%d\n", ans); 31 } 32 return 0; 33 }
HDU 1213 How Many Tables,布布扣,bubuko.com
原文:http://www.cnblogs.com/zzy9669/p/3871689.html