您的位置:首页 > 理论基础 > 数据结构算法

数据结构 并查集 POJ 1611

2016-08-07 20:03 267 查看
#include <cstdio>
#include <math.h>
#include <cstring>
const int N=30005;
int parent
;//并查集
int son
;//用来累加 个数
int n,m;
int find(int x)
{
if(x!=parent[x])
{
return parent[x]=find(parent[x]);
}
else return x;
}
void into()
{
for(int i=0;i<N;i++)
{
parent[i]=i;
son[i]=1;//每个人都是1
}
}
int main()
{

while(scanf("%d%d",&n,&m)!=EOF && n!=0)
{
into();
while(m--)
{
int tmp;//这个社团的人数
int x,y;
scanf("%d",&tmp);
if(tmp==1)
scanf("%d",&x);
else
{
scanf("%d",&x);
tmp--;
while(tmp--)
{
scanf("%d",&y);
int px=find(x);int py=find(y);
if(px!=py)//不在同一个社团 ,就链接起来
{
parent[px]=py;// parent[px]的值被改了,而parent[py]的值没有被改
son[py]+=son[px];//所以py是最下面 所以把累计到px里的值 加到py里
}
}
}
}
printf("%d\n",son[find(0)]); //找到0所在 集合的尾位置,就知道总数了
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: