pku 2524

2009年7月12日 星期日

题目链接:PKU  2524  Ubiquitous  Religions

分类:最基本的并查集

Code:

 1
#include<stdio.h>
 2#define MAXN 50005
 3int parent[MAXN],count;
 4void init(int n)
 5{
 6    int i;
 7    for(i=1;i<=n;i++)parent[i]=-1;
 8}

 9
10int find(int x)
11{
12    if(parent[x]<0return x;
13    else return parent[x]=find(parent[x]);
14}

15
16int 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}

35int 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




posted on 2009-07-12 23:44 蜗牛也Coding 阅读(722) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2009年7月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿(8)

随笔档案(78)

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜