POJ 2524--Ubiquitous Religions

 1 //并查集
 2 #include<iostream>
 3 #include<cstdio>
 4 using namespace std;
 5 
 6 const int maxn=50005;
 7 int f[maxn],cnt;
 8 
 9 int find(int x)
10 {
11 //    if(f[x]!=x)
12 //    {
13 //        f[x]=find(f[x]);
14 //    }
15 //    return f[x];
16     while(x!=f[x])//找根可以递归或递推
17     {
18         x=f[x];
19     }
20     return x;
21 }
22 
23 void unicom(int a,int b)
24 {
25     int root_a=find(a);
26     int    root_b=find(b);
27     if(root_a!=root_b)//注意合并是根节点之间的操作
28     {
29         f[root_b]=root_a;
30         cnt--;//体会这种倒序的想法:减法操作
31     }
32 }
33 
34 int main()
35 {
36     int n,m;
37     int num=1;
38     while(scanf("%d%d",&n,&m)!=EOF&&n&&m)
39     {
40         for(int i=1;i<=n;i++)//initialize all node 
41             f[i]=i;
42         cnt=n;
43         for(int i=1;i<=m;i++)
44         {
45             int a,b;
46             scanf("%d%d",&a,&b);
47             unicom(a,b);
48         }
49         printf("Case %d: %d\n",num,cnt);        
50         num++;
51     }
52     return 0;
53 }

猜你喜欢

转载自www.cnblogs.com/chuanwen-tech/p/10287340.html