标签:
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 30666
|
Accepted: 14860 |
Description
Input
Output
Sample Input
10 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0
Sample Output
Case 1: 1
Case 2: 7
Hint
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <fstream> 5 using namespace std; 6 int f[50005]; 7 8 int find(int x) { 9 if (x != f[x]) 10 f[x] = find(f[x]); 11 return f[x]; 12 } 13 14 void Union(int a, int b) { 15 int f1 = find(a); 16 int f2 = find(b); 17 if (f1 != f2) 18 f[f2] = f1; 19 } 20 21 int main() { 22 //ifstream cin("aaa.txt"); 23 int n, m, test = 1, sum; 24 25 while(scanf("%d%d", &n, &m)){ 26 if (n == 0 && m == 0) 27 break; 28 memset(f, 0, sizeof(f)); 29 30 for(int i = 1; i <= n; i++) { 31 f[i] = i; 32 } 33 34 sum = n; 35 36 for(int i = 1; i <= m; i++) { 37 int a, b; 38 scanf("%d%d", &a, &b); 39 if(find(a) != find(b)){ 40 Union(a, b); 41 sum--; 42 } 43 } 44 45 printf("Case %d: %d\n", test++, sum); 46 47 } 48 //system("pause"); 49 return 0; 50 }
1 #include <stdio.h> 2 #include <iostream> 3 using namespace std; 4 5 const int MAXN = 50005; /*结点数目上线*/ 6 int pa[MAXN]; /*p[x]表示x的父节点*/ 7 int rank1[MAXN]; /*rank[x]是x的高度的一个上界*/ 8 int n, ans; 9 10 void make_set(int x) 11 {/*创建一个单元集*/ 12 pa[x] = x; 13 rank1[x] = 0; 14 } 15 16 int find_set(int x) 17 {/*带路径压缩的查找*/ 18 if(x != pa[x]) 19 pa[x] = find_set(pa[x]); 20 return pa[x]; 21 } 22 23 /*按秩合并x,y所在的集合*/ 24 void union_set(int x, int y) 25 { 26 x = find_set(x); 27 y = find_set(y); 28 if(x == y)return ; 29 ans--; //统计 30 if(rank1[x] > rank1[y])/*让rank比较高的作为父结点*/ 31 { 32 pa[y] = x; 33 } 34 else 35 { 36 pa[x] = y; 37 if(rank1[x] == rank1[y]) 38 rank1[y]++; 39 } 40 } 41 //answer to 2524 42 int main() 43 { 44 int m, i, j = 1, x, y; 45 while(scanf("%d%d", &n, &m)) 46 { 47 if(n == m && m == 0) break; 48 for(i = 1; i <= n; i++) 49 make_set(i); 50 ans = n; 51 for(i = 0; i < m; i++) 52 { 53 scanf("%d%d", &x, &y); 54 union_set(x, y); 55 } 56 printf("Case %d: %d\n", j, ans); 57 j++; 58 } 59 return 0; 60 }
poj 2524 Ubiquitous Religions(宗教信仰)
标签:
原文地址:http://www.cnblogs.com/qinduanyinghua/p/5497699.html