poj 2524

这是一道并查集的简单题目,只要套用并查集的模板就可以了。

题目的意思:输入一个n和m,接下来的m行,给出两个数x和y表示x和y有关系(你可以默认为他们信的一个宗教)。最后让你输出一共可以找到几个不同的宗教。

 1 #include<stdio.h>
2 #include<iostream>
3 #include<string.h>
4 using namespace std;
5 #define N 50010
6 int a[N];
7 int find(int x)
8 {
9 if(a[x]!=x) return a[x]=find(a[x]);
10 return a[x];
11 }
12 int main()
13 {
14 int i;
15 int n,m;
16 int cs=0;
17 while(cin>>n>>m,n+m)
18 {
19 for(i=1;i<=n;i++)
20 a[i]=i;
21 while(m--)
22 {
23 int x,y,root2,root1;
24 cin>>x>>y;
25 root1=find(x);
26 root2=find(y);
27 if(root1!=root2) a[root2]=root1;
28 }
29 cout<<"Case "<<++cs<<": ";
30 int sum=0;
31 for(i=1;i<=n;i++)
32 {
33 if(i==find(i)) sum++;
34 }
35 cout<<sum<<endl;
36 }
37 return 0;
38 }

 

 

posted @ 2012-03-05 18:50  AC_Girl  阅读(165)  评论(0编辑  收藏  举报