poj2254

并查集的基础题。总共n个人,有m组人有相同信仰。问这些人中存在的信仰最多有多少种。

 1 #include<cstdio>
 2 #include<string.h>
 3 #include<iostream>
 4 using namespace std;
 5 const int maxn=50001;
 6 int p[maxn],rank[maxn];
 7 bool vis[maxn];
 8 
 9 int find(int v)
10 {
11     if(p[v]==v)
12     return v;
13     else
14     {
15         p[v]=find(p[v]);
16         return p[v];
17     }
18 }
19 
20 void unions(int x,int y)
21 {
22     x=find(x);
23     y=find(y);
24     if(x==y)
25     return;
26     if(rank[x]>rank[y])
27     p[y]=x;
28     else
29     {
30         p[x]=y;
31         if(rank[x]==rank[y])
32         rank[y]++;
33     }
34 }
35 int main()
36 {
37     //freopen("test.txt","r",stdin);
38     int n,m,T=1;
39     while(scanf("%d%d",&n,&m)!=EOF)
40     {
41         if(n==0&&m==0)
42         return 0;
43         int i,a,b,s1,s2;
44         for(i=0;i<n;i++)
45         {
46             p[i]=i;
47             rank[i]=0;
48         }
49         for(i=0;i<m;i++)
50         {
51             scanf("%d%d",&a,&b);
52             s1=find(a);
53             s2=find(b);
54             unions(s1,s2);
55         }
56         memset(vis,0,sizeof(vis));
57         int ans=0;
58         for(i=0;i<n;i++)
59         {
60             s1=find(i);
61             //printf("s1=%d\n",s1);
62             if(!vis[s1])
63             {
64                 ans++;
65                 vis[s1]=true;
66             }
67         }
68         printf("Case %d: %d\n",T++,ans);
69     }
70     return 0;
71 }
View Code

 

posted @ 2013-06-03 11:47  longlongago  Views(113)  Comments(0Edit  收藏  举报