博客园 首页 私信博主 显示目录 隐藏目录 管理

【模板】最小生成树

#include<bits/stdc++.h>

using namespace std;

const int N = 5010;
const int M = 200010;

int n, m, ans;
int r[N], f[N];
struct node{
    int u, v, w;
}E[M];

template <typename T>
T read(){
    T N(0), F(1);
    char C = getchar();
    for(; !isdigit(C); C = getchar()) if(C == '-') F = -1;
    for(; isdigit(C); C = getchar()) N = N*10 + C-48;
    return N*F;
}

bool cmp(node x, node y){
    return x.w < y.w;
}

void init(){
    for(int i = 1; i <= n; i++) f[i] = i;
    memset(r, 0, sizeof(r));
}

int find(int x){
    return x == f[x] ? x : f[x] = find(f[x]);
}

void mix(int a, int b){
    int fa = find(f[a]);
    int fb = find(f[b]);
    if(fa == fb) return;
    if(r[fa] < r[fb]){
        f[fa] = fb;
    }
    else{
        f[fb] = fa;
        if(r[fa] == r[fb]) r[fa]++;
    }
}

int krus(){
    int em = 0;
    sort(E+1, E+m+1, cmp);

    for(int i = 1; i <= m && em != n-1; i++){
        int fu = find(E[i].u);
        int fv = find(E[i].v);
        if(find(E[i].u) != find(E[i].v)){
            mix(E[i].u, E[i].v);
            ans += E[i].w;
            em++;
        }
    }
    if(em < n-1) ans = -1;
    return ans;
}

int main(){
    n = read<int>(); m = read<int>();

    for(int i = 1; i <= m; i++){
        E[i].u = read<int>();
        E[i].v = read<int>();
        E[i].w = read<int>();
    }

    init();
    printf("%d\n", krus());

    return 0;
}
posted @ 2017-10-13 22:09  Hanser  阅读(107)  评论(0编辑  收藏  举报