| Time Limit: 5000MS | Memory Limit: 65536K | |
| Total Submissions: 25255 | Accepted: 12454 |
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
#include<iostream>
#include<stdio.h>
using namespace std;
#define M 50010
int pre[M];
int ranks[M];
int ans;
void init(int n)
{
for(int i=0;i<n;++i)
{
pre[i]=i;
ranks[i]=1;
}
}
int _find(int x){
if(x==pre[x])return x;
return pre[x]=_find(pre[x]);
}
void _union(int a,int b)
{
int x= _find(a);
int y= _find(b);
if(x==y)return ;
else
{
if(ranks[x]<ranks[y])
{
ranks[y]+=ranks[x];
pre[x]=y;
}
else
{
ranks[x]+=ranks[y];
pre[y]=x;
}
ans--;
}
}
int main(int argc, char *argv[])
{
//freopen("2524.in","r",stdin);
int n,m;
int a,b;
int count=1;
while(scanf("%d%d",&n,&m)!=EOF&&n!=0)
{
init(n);
ans = n;
while(m--)
{
scanf("%d%d",&a,&b);
_union(a,b);
}
printf("Case %d: %d\n",count,ans);
count++;
}
return 0;
}
POJ Ubiquitous Religions (并查集)
原文:http://blog.csdn.net/wdkirchhoff/article/details/41777567