并查集模板

#include<iostream>
#include<algorithm>
#define fori for(i=0;i<n;i++)
#define fori1 for(i=1;i<=n;i++)
#define ll long long
const ll mod = 1e9 + 7;
const int maxn = 30050;
using namespace std;
ll s[maxn + 7];
ll height[maxn + 7];
void init_set()//初始化
{
    s[0] = 0;
    for (int i = 1; i <= maxn; i++)
    {
        s[i] = i;
        height[i] = 0;//树的高度
    }
}
ll find_set(ll x)//查找
{
    ll r = x;//找到根结点
    while (s[r] != r)r = s[r];
    ll i = x, j;
    while (i != r) {
        j = s[i];//用临时变量j记录
        s[i] = r;//把路径上元素的集改为根结点
        i = j;
    }
    return r;
}
void union_set(ll x, ll y)//合并
{
    x = find_set(x);
    y = find_set(y);
    if (height[x] == height[y])
    {
        height[x] = height[x] + 1;
        s[y] = x;//合并,树的高度加一
    }
    else
    {
        if (height[x] < height[y])s[x] = y;//把矮树并到高树上,高树的高度保持不变
        else
            s[y] = x;
    }
}

int main()
{
    ll i, j, k;
    ll n, m, t;
    ll x, y;
    while (cin >> n >> m)
    {
        if (n == 0 && m == 0)
            break;
        init_set();
        while (m--)
        {
            cin >> t;
            for (i = 0; i < t; i++)
            {
                if (i == 0)
                {
                    cin >> x;
                }
                else
                {
                    cin >> y;
                    union_set(x, y);
                }
            }
        }
        ll ans = 0,x=find_set(0);//查找与0连接的点
        fori
        {
            if (find_set(i) == x)
                ans++;
        }
        cout << ans << endl;
        
    }

}

 

posted @ 2020-04-03 17:34  ch_hui  阅读(108)  评论(0编辑  收藏  举报