最小生成树的唯一性

here

a了捏

#include<iostream>
#include<algorithm>
#include<set>

using namespace std;

const int N = 200010;

int n,m;
int p[N];
int f = 0;

//并查集
int find(int x){
    if(p[x] != x) p[x] = find(p[x]);
    return p[x];
}

//结构体存边
struct Edge{
    int a,b,w;

    bool operator < (const Edge &x) const{
        return w < x.w;
    }
} es[N];

int main(){
    cin >> n >> m;

    for(int i = 0;i < m;i ++){
        int a,b,c;
        cin >> a >> b >> c;

        es[i] = {a,b,c};
    }

    int cnt = 0,res = 0;

    for(int i = 1;i <= n;i ++) p[i] = i;

    sort(es,es + m);

    for(int i = 0;i < m;i ++){
        int a = es[i].a,b = es[i].b,w = es[i].w;

        a = find(a),b = find(b);

        if(a != b){
            for(int j = i + 1;j < m && w == es[j].w;j ++){
                int pa = find(es[j].a),pb = find(es[j].b);
                if((pa == a && pb == b) || (pa == b && pb == a)) f = 1;
            }
            p[a] = b;
            res += w;
            cnt ++;
        }

        if(cnt == n - 1) break;
    }   

    set<int> alls;
    for(int i = 1;i <= n;i ++) alls.insert(find(i));

    if(alls.size() == 1){
        cout << res << endl;
        if(f) cout << "No";
        else cout << "Yes";
    }else{
        cout << "No MST" << endl;
        cout << alls.size();
    }
}
posted @ 2021-12-04 21:52  Xuuxxi  阅读(89)  评论(1编辑  收藏  举报