题目链接:http://poj.org/problem?id=2524
并查集的模版题:
#include <cstdio>
#include <cstring>
struct node
{
int pre;
int rankk;
};
node stu[50010];
int n,m;
int find(int x)
{
int r=x;
while(stu[r].pre!=-1)
r=stu[r].pre;
while(r!=x)
{
int p=stu[x].pre;
stu[x].pre=r;
x=p;
}
return r;
}
void unionone(int x,int y)
{
if(stu[x].rankk>stu[y].rankk)
{
stu[y].pre=x;
stu[x].rankk+=stu[y].rankk;
}
else
{
stu[x].pre=y;
stu[y].rankk+=stu[x].rankk;
}
}
int main()
{
int i,x,y,ans,cnt=0;
while(~scanf("%d%d",&n,&m)&&(n||m))
{
ans=0;
for(i=1;i<=n;++i)
{
stu[i].pre=-1;
stu[i].rankk=1;
}
for(i=1;i<=m;++i)
{
scanf("%d%d",&x,&y);
int xx=find(x);
int yy=find(y);
if(xx!=yy)
unionone(xx,yy);
}
for(i=1;i<=n;++i)
{
if(stu[i].pre==-1)
++ans;
}
cnt++;
printf("Case %d: %d\n",cnt,ans);
}
return 0;
}