• The Suspects POJ


    The Suspects POJ - 1611
    知识点:并查集
    我这里把查询和合并进行了优化,喜欢的话可以拿来当模板

    #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;
            
        }
    
    }
  • 相关阅读:
    rmq +二分暴力 hdu 5726
    8.25 ccpc 比赛总结
    莫比乌斯反演题目总结
    HDU 4848 Wow! Such Conquering! (搜索+floyd)
    Codeforces 982 C Cut 'em all!(DFS)
    Codefoces 986C AND Graph(DFS)
    CodeForces 986A Fair(BFS)
    ACM经验贴
    Kattis A+B Problem(FFT)
    CF E. Porcelain (双向dp)
  • 原文地址:https://www.cnblogs.com/ch-hui/p/12623870.html
Copyright © 2020-2023  润新知