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.

62 lines
1.5 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 310;
int n; // n条顶点
int res; // 最小生成树的权值和
2 years ago
2 years ago
// Kruskal用到的结构体
const int M = 2 * N * N; // 无向图*2稠密图N*N
struct Edge {
2 years ago
int a, b, c;
2 years ago
const bool operator<(const Edge &t) const {
2 years ago
return c < t.c;
2 years ago
}
2 years ago
} edge[M];
int el; // 边数
2 years ago
// 并查集
int p[N];
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
// Kruskal算法
int kruskal() {
// 按边的权重排序
2 years ago
sort(edge, edge + el);
2 years ago
// 初始化并查集,注意并查集的初始是从0开始的因为0号是超级源点
for (int i = 0; i <= n; i++) p[i] = i;
// 枚举每条边
for (int i = 0; i < el; i++) {
2 years ago
int a = edge[i].a, b = edge[i].b, c = edge[i].c;
2 years ago
a = find(a), b = find(b);
if (a != b)
2 years ago
p[a] = b, res += c;
2 years ago
}
return res;
}
int main() {
cin >> n;
2 years ago
2 years ago
// 建立超级源点(0 <-> 1~n )
2 years ago
int c;
2 years ago
for (int i = 1; i <= n; i++) {
2 years ago
cin >> c; // 点权转边权
edge[el++] = {0, i, c};
edge[el++] = {i, 0, c};
2 years ago
}
// 本题是按矩阵读入的不是按a,b,c方式读入的
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
2 years ago
cin >> c;
edge[el++] = {i, j, c};
edge[el++] = {j, i, c};
2 years ago
}
// 利用Kruskal计算最小生成树
2 years ago
cout << kruskal() << endl;
2 years ago
return 0;
}