• 【模板】最小生成树


    #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;
    }
    
  • 相关阅读:
    面向对象基础
    JS操作属性和样式
    表单验证
    form标签
    Dreamweaver网页设计代码大全
    最差项目展示
    CSS样式表
    while循环 do while循环 switch
    for循环
    穷举法
  • 原文地址:https://www.cnblogs.com/hanser/p/7663546.html
Copyright © 2020-2023  润新知