您的位置:首页 > 其它

ZOJ 1789

2010-12-04 14:39 363 查看
//2363500 2010-12-02 21:50:28 Accepted 1789 C 10 392 VRS
//1789 SARS隔离 并查集

#include<stdio.h>
#include<string.h>

int setFather[30005];
int setCount[30005];

int Find(int x)
{
int root=x;
while(setFather[root]!=root)
root=setFather[root];
while(setFather[x]!=x)
{
setFather[x]=root;
x=setFather[x];
}
return root;
}

void Union(int x,int y)
{
int rootX=Find(x);
int rootY=Find(y);
if(rootX==rootY)
return;
else if(rootX<rootY) //可以让下标小的作为根结点
{
setFather[rootY]=rootX;
setCount[rootX]+=setCount[rootY];
}
else
{
setFather[rootX]=rootY;
setCount[rootY]+=setCount[rootX];
}
}

int main()
{
int n,m;
int i,j;
int tempNum;
int groupFir,groupSec;
while(scanf("%d %d",&n,&m) && !(n==0 && m==0))
{
for(i=0;i<n;i++)
{
setFather[i]=i;
setCount[i]=1;
}
for(i=0;i<m;i++)
{
scanf("%d %d",&tempNum,&groupFir);
//每次都对当前集合合并,如果有重复的就会合并到前面的集合中,否则生成新的集合
for(j=0;j<tempNum-1;j++)
{
scanf("%d",&groupSec);
Union(groupFir,groupSec);
}
}
printf("%d\n",setCount[0]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: