poj2524(并查集基础基础基础题)_初始化

#include<iostream>
#include<string>
#include<algorithm>
#define M 50005
using namespace std;

int pre[M];
int find(int x) //带状态压缩的查找
{
int y=x,temp;
while(y!=pre[y]) y=pre[y];
while(x!=y)
{
temp=pre[x];
pre[x]=y;
x=temp;
}
return y;
}

void uni(int x,int y)
{
int px,py;
px=find(x);
py=find(y);
if(px==py) return ;
else pre[py]=px;
}


int main()
{
int n,m,t=0,i,x,y,ans;
while(scanf("%d%d",&n,&m),m!=0&&n!=0)
{
for(i=1;i<=n;i++) //初始化
pre[i]=i;

while(m--)
{
scanf("%d%d",&x,&y);
uni(x,y); //合并
}

ans=0;
for(i=1;i<=n;i++)
if(find(i)==i)
ans++;

printf("Case %d: %d\n",++t,ans);
}
return 0;
}