给定结点数为 n,边数为 m 的带权无向连通图 G,所有结点编号为 1,2,⋯,n。
求 G 的最小生成树的边权和。
第一行包含两个整数N、M,表示该图共有N个结点和M条无向边。(N<=5000,M<=200000)
接下来M行每行包含三个整数Xi、Yi、Zi,表示有一条长度为Zi的无向边连接结点Xi、Yi
一个整数表示从G 的最小生成树的边权和。
Kruscal算法即可
7 11 5 4 2 4 2 1 4 3 7 2 2 3 4 3 5 7 5 7 3 3 6 1 1 6 3 4 2 4 3 5 6 3 7 2 1 ------------------------ 7
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; struct bian { int x, y, a; } e[200050]; bool cmp(const bian p, const bian q) { return p.a < q.a; } int n, m, ans, t, father[5050]; int gf(int x) { if (father[x] == x) return(x); father[x] = gf(father[x]); return(father[x]); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].a); for (int i = 1; i <= n; i++) father[i] = i; sort(e + 1, e + m + 1, cmp); for (int i = 1; i <= m; i++) { int fx = gf(e[i].x); int fy = gf(e[i].y); if (fx != fy) { father[fx] = fy; ans += e[i].a; } } printf("%d", ans); return 0; }