You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.1 KiB

#include <bits/stdc++.h>
using namespace std;
const int N = 110;
const int M = 10010;
struct Node { // 用结构体存储每条边
int f, t, w;
bool operator<(const Node &e) const {
return w < e.w;
}
} edges[M];
int p[N];
int find(int x) { // 并查集找根节点
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int n, idx, ans;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) p[i] = i; // 并查集初始化
// 邻接矩阵
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
int w;
cin >> w;
edges[idx++] = {i, j, w}; // 加入当前的边
}
sort(edges, edges + idx); // 对边权进行排序,谁小谁在前
for (int i = 1; i <= idx; i++) { // 枚举每条边
int f = find(edges[i].f), t = find(edges[i].t);
if (f != t) { // 当前两点不连通
ans += edges[i].w; // 更新答案
p[f] = t; // 让两点变连通
}
}
cout << ans << endl;
return 0;
}