Link
解题思路
很经典的模板题
设一个超级起点,所有点建发电站,视为是所有点向超级起点连边
再做最小生成树就ok了
Code
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
struct DT{
int x, y, s;
}a[95000];
int n, s, num, xx, yy, ans, fa[500];
bool cmp(const DT&k, const DT&l) {
return k.s < l.s;
}
int find(int x) {
if (fa[x] == -1) return x;
fa[x] = find(fa[x]);
return fa[x];
}
int main() {
scanf("%d", &n);
for (int i = 0; i <= n; i++)
fa[i] = -1; //我常用的超级起点是0, 所以初值不能设0
for (int i = 1; i <= n; i++) {
scanf("%d", &s);
a[++num].x = 0, a[num].y = i, a[num].s = s; //建发电站-》每个点向0作边
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
scanf("%d", &s);
a[++num].x = j, a[num].y = i, a[num].s = s;
}
sort(a + 1, a + 1 + (n * n + n), cmp); //以下是普通的最小生成树
for (int i = 1; i <= (n * n + n); i++) {
xx = find(a[i].x), yy = find(a[i].y);
if (xx != yy) {
fa[xx] = yy;
ans += a[i].s;
}
}
printf("%d", ans);
}