constint MAXV = 110; constint MAXE = 10010; structedge { int u, v; int cost; } E[MAXE];
int father[MAXV]; intfindFather(int x){ int a = x; while (father[x] != x) { x = father[x]; } // 找到顶层 => x while (a != father[a]) { // 路径压缩 int z = a; a = father[a]; father[z] = x; } return x; } // n是顶点数,m是边数 intkruskal(int n, int m){ int ans = 0, cnt = 0; for (int i = 0; i < n; i++) father[i] = i; // 并查集初始化 sort(E.begin(), E.end(), [&](edge a, edge b) { return a.cost < b.cost; }); for (auto p: E) { int faU = findFather(p.u); int faV = findFather(p.v); if (faU != faV) { // 不是一个连通分量 father[faU] = faV; ans += p.cost; cnt++; if (cnt == n - 1) break; } } if (cnt != n - 1) return-1; elsereturn ans; }