最小生成树的唯一性

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;
                else break;
            }
            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();
    }
}
上一篇:关系型数据库与非关系型数据库的区别汇总


下一篇:leetcode429_N叉树的遍历