其他分享
首页 > 其他分享> > 【数据结构】并查集

【数据结构】并查集

作者:互联网

namespace DisjointSet {

    const int MAXN = 200000 + 5;

    int n;
    int rt[MAXN + 5];
    int sz[MAXN + 5];

    void Init(int n): n(n) {
        for(int i = 1; i <= n; i++) {
            rt[i] = i;
            sz[i] = 1;
        }
    }

    int Find(int u) {
        int r = rt[u];
        while(rt[r] != r)
            r = rt[r];
        int t;
        while(rt[u] != r) {
            t = rt[u];
            rt[u] = r;
            u = t;
        }
        return r;
    }

    bool Union(int u, int v) {
        u = Find(u), v = Find(v);
        if(u == v)
            return false;
        else {
            if(sz[u] < sz[v])
                swap(u, v);
            rt[v] = u;
            sz[u] += sz[v];
            return true;
        }
    }
    
}

标签:200000,rt,DisjointSet,const,int,查集,MAXN,数据结构
来源: https://www.cnblogs.com/purinliang/p/13666017.html