标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35567 Accepted Submission(s): 18841
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 int n, m; 6 int par[1010]; 7 int road[1010]; 8 9 //经过路径压缩后的并查集 10 int find(int x) 11 { 12 return par[x] == x ? x : par[x] = find(par[x]); 13 } 14 void merge(int x, int y) 15 { 16 x = find(x); 17 y = find(y); 18 if(x != y) 19 { 20 par[x] = y; 21 } 22 23 } 24 int main() 25 { 26 int a, b; 27 while(scanf("%d %d", &n, &m) != EOF && n) 28 { 29 int ans = 0; 30 for(int i = 1; i <= n; i++) 31 { 32 par[i] = i; 33 } 34 for(int i = 1; i <= m; i++) 35 { 36 scanf("%d %d", &a, &b); 37 merge(a, b); //归并所有有关联的节点 38 } 39 memset(road, 0, sizeof(road)); 40 for(int i = 1; i <= n; i++) //遍历所有的节点,查找根节点 41 { 42 road[find(i)] = 1; 43 } 44 for(int i = 1;i <= n; i++) //统计根节点数目 45 { 46 if(road[i]) 47 { 48 ans++; 49 } 50 } 51 printf("%d\n", ans-1); //合并到一个节点上,要-1 52 } 53 }
标签:
原文地址:http://www.cnblogs.com/vencentX/p/4540106.html