您的位置:首页 > 其它

POJ 1611 The Suspects(并查集)

2013-07-15 17:34 148 查看
经典的并查集题目。著名的非典问题 = = 。PS:最近H7N9也挺厉害的。各位小心

#include <cstdio>

using namespace std;

int father[30005],num[30005];

int main()
{
void Init_set(int x);
int  Find_set(int x);
void Union_set(int a,int b);
int n,m;
int count,first,b;
while(scanf("%d %d",&n,&m)!=EOF && n!=0)
{
Init_set(n);
while(m--)
{
scanf("%d %d",&count,&first);
for(int j=1;j<count;j++)
{
scanf("%d",&b);
Union_set(first,b);
}
}
printf("%d\n",num[Find_set(0)]);
}
return 0;
}

void Init_set(int x)   //初始化
{
for(int i=0;i<x;i++)
{
father[i]=i;
num[i]=1;
}
}

int Find_set(int x)
{
if(father[x]!=x)
{
father[x]=Find_set(father[x]);
}
return father[x];
}

void Union_set(int a,int b)   //将所有的点都并到同一个根上。
{
int x=Find_set(a);
int y=Find_set(b);
if(x==y)
{
return;
}
if(num[x]<=num[y])   //记录根上的点的数目。
{
father[x] = y;
num[y]+=num[x];
}
else
{
father[y]=x;
num[x]+=num[y];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: