http://poj.org/problem?id=1611
做两个并查集调解下,顺便凑点数,嘻嘻。。。
三个方法 make_set(),find_root(),union_set()做个模板吧
有的并查集构图还是得好好弄的
代码:
#include<iostream>
#include<cstdio>
#define MAX 50005
using namespace std;
int root[MAX],level[MAX];
int n;
void make_set()
{
for(int i=0;i<n;i++)
{
root[i]=i;
level[i]=0;
}
}
int find_root(int x)
{
int r=x;
while(r!=root[r])
r=root[r];
int i,j=x;
while(r!=root[j])
{
i=root[j];
root[j]=r;
j=i;
}
return r;
}
void union_set(int a,int b)
{
int x,y;
x=find_root(a);
y=find_root(b);
if(x==y)return ;
if(level[x]<level[y])
root[x]=y;
else
{
root[y]=x;
if(level[x]==level[y])
level[x]++;
}
return ;
}
int main()
{
int m;
int cnt,x,y;
while(~scanf("%d%d",&n,&m))
{
make_set();
if(n==0&&m==0)break;
while(m--)
{
scanf("%d%d",&cnt,&x);
cnt--;
while(cnt--)
{
scanf("%d",&y);
union_set(x,y);
}
}
int ans=1,rr=find_root(0);
for(int i=1;i<n;i++)
{
if(find_root(i)==rr)
ans++;
}
printf("%d\n",ans);
}
return 0;
}