• Boruvka最小生成树模板


    #include<bits/stdc++.h> 
    #define Pair pair<int, int> 
    #define fi first
    #define se second
    #define pb push_back
    #define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
    char buf[(1 << 22)], *p1 = buf, *p2 = buf;
    using namespace std;
    const int MAXN = 5001;
    inline int read() {
        char c = getchar(); int x = 0, f = 1;
        while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
        while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
        return x * f;
    }
    int N, M;
    namespace DSU {  
        int fa[MAXN], siz[MAXN];
        void init(int N) {
            for(int i = 1; i <= N; i++) fa[i] = i, siz[i] = 1;
        }
        int find(int x) {
            return fa[x] == x ? fa[x] : fa[x] = find(fa[x]);
        }
        void unionn(int x, int y) {
            int fx = find(x), fy = find(y);
            if(siz[fx] > siz[fy]) swap(fx, fy);
            fa[fx] = fy; siz[fy] += siz[fx];
        }
    };
    using namespace DSU;  //并查集找连通块
    vector<Pair> v[MAXN];
    int link[MAXN], val[MAXN];
    void Boruvka() {
        init(N); int ans = 0;
        bool flag;
        do {
            flag = 0;
            memset(link, 0, sizeof(link));
            memset(val, 0x3f, sizeof(val));
            for(int x = 1; x <= N; x++) {  //  更新联通块最小的边
                int fx = find(x);
                for(auto &tmp : v[x]) {
                    int to = tmp.fi, w = tmp.se, fy = find(to);
                    if(fx == fy || (w > val[fx])) continue; //更新最小的边
                    link[fx] = fy; val[fx] = w;  
                }
            }
            for(int x = 1; x <= N; x++) {
                int fx = find(x);
                if((link[fx]) && find(fx) != find(link[fx]))  // 连接连通块
                    unionn(fx, link[fx]), ans += val[fx], flag = 1; 
            }   
        }while(flag);
        int f1 = find(1);
        for(int i = 2; i <= N; i++) if(find(i) != f1) return (void) puts("orz"); //图不连通
        cout << ans;
    }
    signed main() {
        N = read(); M = read();
        for(int i = 1; i <= M; i++) {
            int x = read(), y = read(), w = read();
            v[x].push_back({y, w});
            v[y].push_back({x, w});
        }
        Boruvka();
    }
  • 相关阅读:
    【总结】——Repeater控件详细应用
    【SelfIntroduction in Optional Course】
    【软考之后的思考】
    打印菱形图案printDiamond
    【这是来自Word 2010 的Test】
    【30岁前挣够500万】
    【总结 CKEditor 和 CKFinder 的配置和使用】
    linux压缩(解压缩)命令详解 [转]
    关于吞吐量和并发度 [转]
    Linux的五个查找命令 [转]
  • 原文地址:https://www.cnblogs.com/acmLLF/p/13443707.html
Copyright © 2020-2023  润新知