[CF1242B] 0-1 MST - disjoint-set

There is a complete graph, \ (n-\) nodes, have \ (m \) side of the right sides of \ (1 \) , and the rest are \ (0 \) , which \ (m \) edges will Give you. Ask your weight minimum spanning tree of this graph.

Solution

The \ (1 \) side considered absent, then the final answer is \ (0 \) number of block edges forming a communication \ (- 1 \)

Sequentially scanning all points, to a point \ (I \) , enumerated by \ ([1, i-1 ] \) set already formed \ (J \) , if the \ (I \) to \ (J \) connected is smaller than the number of sides \ (J \) size, then it indicates that there must be \ (0 \) side, then the \ (I \) where the set of the set \ (J \) combined

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int N = 500005;

int n,m,t1,t2,fa[N],sz[N],bel[N];
vector <int> g[N];

int find(int p) {
    return p==fa[p] ? p : fa[p]=find(fa[p]);
}

void merge(int p,int q) {
    p=find(p); q=find(q);
    if(p!=q) {
        fa[p]=q;
        sz[q]+=sz[p];
    }
}

signed main() {
    ios::sync_with_stdio(false);
    vector <int> st;
    cin>>n>>m;
    for(int i=1;i<=m;i++) {
        cin>>t1>>t2;
        g[max(t1,t2)].push_back(min(t1,t2));
    }
    for(int i=1;i<=n;i++) {
        fa[i]=i;
        sz[i]=1;
    }
    for(int i=1;i<=n;i++) {
        map<int,int> cnt;
        for(int j:g[i]) cnt[find(j)]++;
        for(int j:st) {
            if(find(i)==find(j)) continue;
            if(cnt[find(j)]<sz[find(j)]) merge(i,j);
        }
        if(find(i)==i) st.push_back(i);
    }
    int ans=0;
    for(int i=1;i<=n;i++) if(find(i)==i) ++ans;
    cout<<ans-1;
}

Guess you like

Origin www.cnblogs.com/mollnn/p/12564108.html