pku 2524
2009年7月12日 星期日
題目鏈接:PKU 2524 Ubiquitous Religions
分類:最基本的并查集
Code:
1
#include<stdio.h>
2
#define MAXN 50005
3
int parent[MAXN],count;
4
void init(int n)
5

{
6
int i;
7
for(i=1;i<=n;i++)parent[i]=-1;
8
}
9
10
int find(int x)
11

{
12
if(parent[x]<0) return x;
13
else return parent[x]=find(parent[x]);
14
}
15
16
int Union(int x,int y)
17

{
18
int root1=find(x),root2=find(y);
19
if(root1==root2) return root1;
20
count--;
21
if(parent[root1]<parent[root2])
22
{
23
parent[root1]+=parent[root2];
24
parent[root2]=root1;
25
return root1;
26
}
27
else
28
{
29
parent[root2]+=parent[root1];
30
parent[root1]=root2;
31
return root2;
32
}
33
34
}
35
int main()
36

{
37
int n,m,i,a,b,ccase=1;
38
while(scanf("%d%d",&n,&m)!=EOF)
39
{
40
if(!m&&!n)break;
41
init(n);
42
count=n;
43
for(i=0;i<m;i++)
44
{
45
scanf("%d%d",&a,&b);
46
Union(a,b);
47
}
48
printf("Case %d: %d\n",ccase++,count);
49
50
}
51
return 0;
52
}
53
題目鏈接:PKU 2524 Ubiquitous Religions
分類:最基本的并查集
Code:
1

2

3

4

5



6

7

8

9

10

11



12

13

14

15

16

17



18

19

20

21

22



23

24

25

26

27

28



29

30

31

32

33

34

35

36



37

38

39



40

41

42

43

44



45

46

47

48

49

50

51

52

53
