题意
题目链接
sol
自己yy着写了一下boruvka算法。
算法思想很简单,就是每次贪心的用两个联通块之间最小的边去合并。
复杂度(o(n log n)),然鹅没有kruskal跑的快,但是好像在一类生成树问题上很有用
#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, -1, 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(); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/604483.html