标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 44539 Accepted Submission(s): 23611
1 #include <cstdio> 2 3 const int MAXN = 1000; 4 int f[MAXN+10]; 5 int n, m; 6 int a, b; 7 8 int find(int x) 9 { 10 return x == f[x] ? x : f[x] = find(f[x]); 11 } 12 13 void merge(int a, int b) 14 { 15 int t1 = find(a); 16 int t2 = find(b); 17 if(t1 != t2) 18 f[t1] = t2; 19 } 20 21 int main() 22 { 23 while(scanf("%d%d", &n, &m), n){ 24 for(int i = 1; i <= n; ++i) 25 f[i] = i; 26 while(m--){ 27 scanf("%d%d", &a, &b); 28 merge(a, b); 29 } 30 int ans = 0; 31 for(int i = 1; i <= n; ++i){ 32 if(f[i] == i) 33 ++ans; 34 } 35 printf("%d\n", --ans); 36 } 37 return 0; 38 }
标签:
原文地址:http://www.cnblogs.com/inmoonlight/p/5543624.html