失踪百景

惯性生存者

导航

kuangbin_UnionFind B (POJ 1611)

过程是模板 merge完后扫一下几个跟0同祖先节点就是答案了

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
const int MAX=30005;
int father[MAX];
int findfather(int x)
{
    while(x!=father[x])
        x=father[x];
    return x;
}
void merge(int x,int y)
{
    x=findfather(x);
    y=findfather(y);
    if(x!=y) father[x]=y;
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m),n||m)
    {
        int ans=0;
        for(int i=0;i<n;i++)
            father[i]=i;
        while(m--)
        {
            int k,fir,tmp;
            scanf("%d%d",&k,&fir);
            k--;
            while(k--)
            {
                scanf("%d",&tmp);
                merge(fir,tmp);
            }
        }
        int ex=findfather(0);
        for(int i=0;i<n;i++)
            if(findfather(i)==ex) ans++;
        printf("%d\n",ans);
    }
    return 0;
}

(似乎这个时候代码还很丑)

posted on 2015-12-20 00:56  失踪百景  阅读(143)  评论(0编辑  收藏  举报