【洛谷】P1546 [USACO3.1] 最短网络 Agri-Net 的题解
【洛谷】P1546 [USACO3.1] 最短网络 Agri-Net 的题解
题目传送门
题解
首先,初始化,很简单这里就不多赘述了。
然后重复 n − 1 n - 1 n−1 次
-
取顶点 v ∈ V − s v \in V - s v∈V−s,使得 w [ u ] [ v ] = min w [ u ] [ v ] ∣ u ∈ s , v ∈ V − s , [ u ] [ v ] ∈ E w[u][v] = \min{w[u][v] \mid u \in s, v \in V - s, [u][v] \in E} w[u][v]=minw[u][v]∣u∈s,v∈V−s,[u][v]∈E
-
S = S + v S = S + {v} S=S+v; t o t = t o t + w [ u ] [ v ] tot = tot + w[u][v] tot=tot+w[u][v]
-
For V-S 中的每个顶点
v do Relax(u, v, W[u][v])
最后 t o t tot tot 为 MST 的总权值。
PS:可以使用二叉堆来实现每步的 DeleteMin(ExtractMin) 操作,可将算法复杂度从 O ( v 2 ) O(v^2) O(v2) 降至 O ( V + E log v ) O(V + E \log v) O(V+Elogv)。推荐稀疏图qaq。
代码
#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int fa[105];
int find(int x) {return x == fa[x] ? x : fa[x] = find(fa[x]);}
int n, en, ans;
struct node {
int x, y, w;
}E[10005];
bool cmp (const node a, const node b) {return a.w < b.w;}
int main() {
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
n = read();
for (int i = 1; i <= n; i ++) {
fa[i] = i;
}
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= n; j ++) {
int in;
in = read();
if (i >= j) continue;
E[++ en].x = i;
E[en].y = j;
E[en].w = in;
}
}
sort (E + 1, E + en + 1, cmp);
for (int i = 1; i <= en; i ++) {
if (find(E[i].x) == find(E[i].y)) {
continue;
}
ans += E[i].w;
fa[find(E[i].x)] = find(E[i].y);
}
write(ans);
return 0;
}