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
|
#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; }
|