标签:des style blog http color os strong io
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 23997 | Accepted: 11807 |
Description
Input
Output
Sample Input
10 9 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 10 4 2 3 4 5 4 8 5 8 0 0
Sample Output
Case 1: 1 Case 2: 7
Hint
Source
1 #include <iostream>
2 #include <stdio.h>
3 using namespace std;
4
5 #define MAXN 50010
6
7 int par[MAXN]; //par[x]表示x的父节点
8 int n;
9
10 void Init() //初始化
11 {
12 int i;
13 for(i=1;i<=n;i++)
14 par[i] = i;
15 }
16
17 int Find(int x) //查询x的根节点并路径压缩
18 {
19 if(par[x]!=x)
20 par[x] = Find(par[x]);
21 return par[x];
22 }
23
24 void Union(int x,int y) //合并x和y所在集合
25 {
26 par[Find(x)] = Find(y);
27 }
28
29 int main()
30 {
31 int m,x,y,i,Case=1;
32 while(scanf("%d%d",&n,&m)!=EOF){
33 if(n==0 && m==0)
34 break;
35 //初始化
36 Init();
37 //m次询问
38 while(m--){
39 scanf("%d%d",&x,&y);
40 Union(x,y);
41 }
42 int ans = n;
43 for(i=1;i<=n;i++) //统计
44 if(par[i]!=i)
45 --ans;
46 printf("Case %d: %d\n",Case++,ans);
47 }
48 return 0;
49 }
Freecode : www.cnblogs.com/yym2013
poj 2524:Ubiquitous Religions(并查集,入门题),布布扣,bubuko.com
poj 2524:Ubiquitous Religions(并查集,入门题)
标签:des style blog http color os strong io
原文地址:http://www.cnblogs.com/yym2013/p/3877111.html