Ubiquitous Religions--POJ 2524

1、解题思路:并查集。

2、注意事项:借用father[]、rank[]两个数组记录的小技巧。

3、实现方法:

1 #include<iostream>
2 #define M 50010
3 using namespace std;
4
5 int father[M],rank[M],ans;
6
7 void Makeset(int x)
8 {
9 father[x]=x;
10 rank[x]=0;
11 }
12
13 int Findfather(int x)
14 {
15 if(x!=father[x])
16 father[x]=Findfather(father[x]);
17 return father[x];
18 }
19
20 void Union(int x,int y)
21 {
22 int a=Findfather(x);
23 int b=Findfather(y);
24 if(a!=b)
25 {
26 if(rank[a]>rank[b])
27 father[b]=a;
28 else
29 {
30 if(rank[a]==rank[b])
31 rank[b]++;
32 father[a]=b;
33 }
34 ans--;
35 }
36 }
37
38 int main()
39 {
40 int i,j,n,m,tmp1,tmp2,cnt=0;
41 while(cin>>n>>m)
42 {
43 if(!n && !m)
44 break;
45 for(j=1;j<=n;j++)
46 Makeset(j);
47 ans=n;
48 for(i=0;i<m;i++)
49 {
50 scanf("%d %d",&tmp1,&tmp2);
51 Union(tmp1,tmp2);
52 }
53 cout<<"Case "<<++cnt<<": "<<ans<<endl;
54 }
55 return 0;
56 }

 

 

 

posted @ 2010-07-22 21:13  勇泽  阅读(209)  评论(0编辑  收藏  举报