859. Kruskal算法求最小生成树

  1. 按边权把边从小到大排序
  2. 用并查集加边
  3. 检查是否为连通图
#include<iostream>
#include<algorithm>

using namespace std;

const int N = 100010, E = 200010;

struct edge{
    int a, b, w;
    
    bool operator <(const edge &e){
        return w < e.w;
    }
}edges[E];

int n, m;
int p[N];

int find(int x){
    if(x != p[x]) p[x] = find(p[x]);
    return p[x];
}

int kruskal(){
    int res = 0, cnt = 0;
    for(int i = 1; i <= m; i ++){
        int a = edges[i].a, b = edges[i].b, w = edges[i].w;
        if(find(a) != find(b)){
            p[find(a)] = find(b);
            cnt ++;
            res += w;
        }
    }
    
    if(cnt < n - 1) res = -1;
    return res;
}

int main(){
    cin >> n >> m;
    
    for(int i = 1; i <= n; i ++) p[i] = i;
    
    for(int i = 1; i <= m; i ++){
        int a, b, w;
        cin >> a >> b >> w;
        
        edges[i] = {a, b, w};
    }
    
    sort(edges + 1, edges + m + 1);
    
    int k = kruskal();
    if(~ k) cout << k;
    else puts("impossible");
    
    return 0;
}
posted @ 2020-08-30 11:21  yys_c  阅读(115)  评论(0编辑  收藏  举报