23333......简单的并查集模板。就是被并查集递归式路径压缩RE坑过。。。学习一下非递归式路径压缩。

附代码:

#include<stdio.h>
#include<iostream>
#include<string.h>
#define maxn 30100
using namespace std;

int fa[maxn];
int n, m, k;

void init()
{
    for (int i=0; i<=n; ++i)
        fa[i] = i;
}

//int find1(int v)  // 递归式路径压缩查找
//{
//    if (fa[v] == v) return v;
//    return fa[v] = find1(fa[v]);
//}

int find1(int v)
{
    int k, j, r;
    r = v;
    while (r != fa[r])
        r = fa[r];
    k = v;
    while(k != r)
    {
        j = fa[k];
        fa[k] = r;
        k = j;
    }
    return r;
}

void unin(int u, int v)
{
    int fau = find1(u);
    int fav = find1(v);
    if (fau != fav)
        fa[fau] = fav;
}

int main()
{
    while (~scanf("%d%d", &n, &m))
    {
        if (n ==0 && m == 0)
            break;
        init();
        while(m--)
        {
            scanf("%d", &k);
            int t, tt;
            if (k != 0)
                scanf("%d", &t);
            for (int i=1; i<k; ++i)
            {
                scanf("%d", &tt);
                unin(t, tt);
            }
        }
        int num = 0;
        for (int i=0; i<n; ++i)
        {
            if (find1(i) == find1(0))
                num++;
        }
        printf("%d\n", num);
    }
    return 0;
}

posted on 2015-06-15 20:48  小小八  阅读(175)  评论(0编辑  收藏  举报