yaoxi-std 的博客

$\text{开}\mathop{\text{卷}}\limits^{ju\check{a}n}\text{有益}$

0%

P4716 【模版】最小树形图

P4716 【模版】最小树形图

题面

题目链接

解法

模版题没啥好说的,用$zl$算法即可。

步骤如下:

  1. 对于每个除了根节点之外的节点,令其边权最小的入边为$fa_u$,边权为$mn_u$。
  2. 判断是否有节点没有入边,若没有则无解,直接返回$-1$。否则答案加上$mn_u$。
  3. 将图中这些边形成的环全部缩点,并重新编号。
  4. 若图中无环,结束算法,返回当前答案。
  5. 将不在环中的点也重新编号。
  6. 对于每条边$(u,v,w)$,将$w$减去$mn_v$。
  7. 更新变量$n$和$rt$,清空最大编号,重复步骤$1$。

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* @file: P4716.cpp
* @author: yaoxi-std
* @url: https://www.luogu.com.cn/problem/P4716
*/
// #pragma GCC optimize ("O2")
// #pragma GCC optimize ("Ofast", "inline", "-ffast-math")
// #pragma GCC target ("avx,sse2,sse3,sse4,mmx")
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define resetIO(x) \
freopen(#x ".in", "r", stdin), freopen(#x ".out", "w", stdout)
#define debug(fmt, ...) \
fprintf(stderr, "[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
template <class _Tp>
inline _Tp& read(_Tp &x) {
bool sign = false;
char ch = getchar();
long double tmp = 1;
for (; !isdigit(ch); ch = getchar())
sign |= (ch == '-');
for (x = 0; isdigit(ch); ch = getchar())
x = x * 10 + (ch ^ 48);
if (ch == '.')
for (ch = getchar(); isdigit(ch); ch = getchar())
tmp /= 10.0, x += tmp * (ch ^ 48);
return sign ? (x = -x) : x;
}
template <class _Tp>
inline void write(_Tp x) {
if (x < 0)
putchar('-'), x = -x;
if (x > 9)
write(x / 10);
putchar((x % 10) ^ 48);
}
const int MAXN = 150;
const int MAXM = 1e4 + 10;
const int INF = 0x3f3f3f3f3f3f3f3f;
struct Edge {
int u, v, w;
} e[MAXM];
int n, m, r;
int tot, head[MAXN], nxt[MAXM];
int mn[MAXN], fa[MAXN], tp[MAXN], lp[MAXN];
void addedge(int u, int v, int w) {
e[++tot] = {u, v, w};
nxt[tot] = head[u], head[u] = tot;
}
int mdst(int rt) {
int ret = 0, tn = 0;
while (true) {
fill(fa, fa + n + 1, 0);
fill(tp, tp + n + 1, 0);
fill(lp, lp + n + 1, 0);
fill(mn, mn + n + 1, INF);
for (int i = 1; i <= m; ++i)
if (e[i].u != e[i].v && e[i].w < mn[e[i].v])
mn[e[i].v] = e[i].w, fa[e[i].v] = e[i].u;
mn[rt] = 0;
for (int i = 1; i <= n; ++i) {
ret += mn[i];
if (mn[i] == INF)
return -1;
}
for (int u = 1; u <= n; ++u) {
int v = u;
while (v != rt && tp[v] != u && !lp[v])
tp[v] = u, v = fa[v];
if (v != rt && !lp[v]) {
lp[v] = ++tn;
for (int k = fa[v]; k != v; k = fa[k])
lp[k] = tn;
}
}
if (!tn)
break;
for (int i = 1; i <= n; ++i)
if (!lp[i])
lp[i] = ++tn;
for (int i = 1; i <= m; ++i)
e[i].w -= mn[e[i].v], e[i].u = lp[e[i].u], e[i].v = lp[e[i].v];
n = tn, rt = lp[rt], tn = 0;
}
return ret;
}
signed main() {
read(n), read(m), read(r);
for (int i = 1; i <= m; ++i) {
int u, v, w;
read(u), read(v), read(w);
addedge(u, v, w);
}
write(mdst(r)), putchar('\n');
return 0;
}