Ubiquitous Religions
http://poj.org/problem?id=2524
View Code
1 #include <stdio.h> 2 int father[50001] ; 3 int find(int x) 4 { 5 while(x!=father[x]) 6 x = father[x] ; 7 return x ; 8 } 9 void merge(int x,int y) 10 { 11 int fx , fy ; 12 fx = find(x) ; 13 fy = find(y) ; 14 if(fx!=fy) 15 father[fx] = fy; 16 } 17 int main() 18 { 19 int i, a, b, m, n ; 20 int count = 1 ; 21 while(scanf("%d%d",&n,&m),n!=0,m!=0) 22 { 23 for(i=1; i<=n; i++ ) 24 father[i] = i ; 25 for(i=1; i<=m; i++) 26 { 27 scanf("%d %d", &a, &b) ; 28 merge(a, b) ; 29 } 30 int num = 0 ; 31 32 for(i=1; i<=n; i++) 33 if(father[i]==i) 34 num++ ; 35 printf("Case %d: %d\n", count++, num) ; 36 } 37 return 0; 38 }
2.宗教信仰种类的最大值为学生数n,因此一开始把n个学生作为n个集合,
对给出的每对大学生 x和 y,如果他们在不同的集合,就合并他们,然后宗教数减一
代码如下:
View Code
1 #include <stdio.h> 2 int father[50001] ; 3 int num ; 4 int find(int x) 5 { 6 while(x!=father[x]) 7 x = father[x] ; 8 return x ; 9 } 10 void merge(int x,int y) 11 { 12 int fx , fy ; 13 fx = find(x) ; 14 fy = find(y) ; 15 if(fx!=fy) 16 { 17 father[fx] = fy; 18 num-- ; 19 } 20 } 21 int main() 22 { 23 int i, a, b, m, n ; 24 int count = 1 ; 25 while(scanf("%d%d",&n,&m),n!=0,m!=0) 26 { 27 for(i=1; i<=n; i++ ) 28 father[i] = i ; 29 num = n ; 30 for(i=1; i<=m; i++) 31 { 32 scanf("%d %d", &a, &b) ; 33 merge(a, b) ; 34 } 35 printf("Case %d: %d\n", count++, num) ; 36 } 37 return 0; 38 }