poj 1611 分类: poj templates 2015-04-03 14:48 33人阅读 评论(0) 收藏
并查集,启发式合并
#include<map>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>
const int MAXN = 3e4+5;
int n , m;
int fa[MAXN] = {0};
int size[MAXN] = {0};
int find_fa(int x)
{
if(fa[x] == x)return x;
else
{
fa[x] = find_fa(fa[x]);
return fa[x];
}
}
void gather(int u,int v)
{
u = find_fa(u), v = find_fa(v);
if(u == v)return;
if(size[u] < size[v])std::swap(u,v);
fa[v] = u, size[u] += size[v];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("poj1611.in","r",stdin);
freopen("poj1611.out","w",stdout);
#endif
while(1)
{
scanf("%d%d",&n,&m);
if(!n && !m)break;
for(int i = 1; i <= n ; i++)fa[i] = i, size[i] = 1;
for(int i = 1; i <= m;i++)
{
int len, h;
scanf("%d",&len);
if(!len)continue;
scanf("%d",&h); h++;
for(int j = 1; j < len; j++)
{
int s; scanf("%d",&s);
++s; gather(h,s);
}
}
printf("%d\n",size[find_fa(1)]);
}
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。