P4716 【模板】最小树形图

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include<bits/stdc++.h>
using namespace std;
const int MAXn = 1e2;
const int MAXm = 1e4;
const int INF = 0x3f3f3f3f;

template <typename T>
inline void read(T &a) {
char c;for (c = getchar(); (c < '0' || c > '9') && c != '-'; c = getchar());bool f = c == '-';T x = f ? 0 : (c ^ '0');for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {x = x * 10 + (c ^ '0');}a = f ? -x : x;
}
template <typename T, typename ...Argv>
inline void read(T &a, Argv &...argv) {
read(a), read(argv...);
}

int cntnd, eg[MAXn + 10][MAXn + 10], tmpeg[MAXn + 10][MAXn + 10];
int pre[MAXn + 10];

bool vis[MAXn + 10];
int CheckCon(int cur) {
vis[cur] = 1;
int ans = 1;
for (int i = 1; i <= cntnd; ++i) {
if (eg[cur][i] == INF || vis[i]) continue;
ans += CheckCon(i);
}
return ans;
}

int cntdfs, dfs[MAXn + 10], low[MAXn + 10];
int cntscc, inscc[MAXn + 10];
int top, stk[MAXn + 10]; bool instk[MAXn + 10];
void Tarjan(int cur) {
dfs[cur] = low[cur] = ++cntdfs;
stk[++top] = cur; instk[cur] = 1;
if (pre[cur]) {
if (!dfs[pre[cur]]) {
Tarjan(pre[cur]);
low[cur] = min(low[cur], low[pre[cur]]);
} else if (instk[pre[cur]]) {
low[cur] = min(low[cur], dfs[pre[cur]]);
}
}
if (dfs[cur] == low[cur]) {
int x;
++cntscc;
do {
x = stk[top--]; instk[x] = 0;
inscc[x] = cntscc;
} while (x != cur);
}
}

int n, m, root, ans;
signed main() {
read(n, m, root);
cntnd = n;
memset(eg, 0x3f, sizeof(eg));
for (int i = 1, u, v, w; i <= m; ++i) {
read(u, v, w);
if (u == v) continue;
eg[u][v] = min(eg[u][v], w);
}
if (CheckCon(root) != cntnd) {
puts("-1");
return 0;
}
while (true) {
for (int i = 1; i <= cntnd; ++i) {
pre[i] = i;
if (i == root) continue;
for (int j = 1; j <= cntnd; ++j) {
if (eg[j][i] < eg[pre[i]][i]) {
pre[i] = j;
}
}
}
memset(dfs, 0, sizeof(dfs));
cntdfs = cntscc = 0;
for (int i = 1; i <= cntnd; ++i) {
if (!dfs[i]) Tarjan(i);
}
if (cntscc == cntnd) {
for (int i = 1; i <= cntnd; ++i) {
if (i == root) continue;
ans += eg[pre[i]][i];
}
break;
}
for (int i = 1; i <= cntnd; ++i) {
if (i == root) continue;
if (inscc[pre[i]] == inscc[i]) ans += eg[pre[i]][i];
}
memset(tmpeg, 0x3f, sizeof(tmpeg));
for (int i = 1, x = inscc[i]; i <= cntnd; ++i, x = inscc[i]) {
for (int j = 1, y = inscc[j]; j <= cntnd; ++j, y = inscc[j]) {
if (eg[i][j] == INF || eg[pre[j]][j] == INF || x == y) continue;
if (inscc[pre[j]] != y) {
tmpeg[x][y] = min(tmpeg[x][y], eg[i][j]);
} else {
tmpeg[x][y] = min(tmpeg[x][y], eg[i][j] - eg[pre[j]][j]);
}
}
}
memcpy(eg, tmpeg, sizeof(eg));
cntnd = cntscc;
root = inscc[root];
}
printf("%d\n", ans);
return 0;
}