|
| 1 | +// 最小费用最大流,增加S,T,容量为2 |
| 2 | +// pku 2135 |
| 3 | +#include <iostream> |
| 4 | +#include <stdio.h> |
| 5 | +#include <algorithm> |
| 6 | +#include <ctime> |
| 7 | + |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +const int maxn = 2005; |
| 11 | +const int maxm = 100005; |
| 12 | +const int inf = 0x2f2f2f2f; |
| 13 | + |
| 14 | +int n, m; |
| 15 | +int d[maxn], q[65537], v[maxn], pre[maxn], preh[maxn]; |
| 16 | +int vpt[maxm], next[maxm], head[maxm], flow[maxm], cost[maxm]; |
| 17 | +int l = 1; |
| 18 | + |
| 19 | +void add (int a, int b, int f, int c) { |
| 20 | + vpt[++ l] = b; |
| 21 | + next[l] = head[a]; |
| 22 | + head[a] = l; |
| 23 | + flow[l] = f; |
| 24 | + cost[l] = c; |
| 25 | + vpt[++ l] = a; |
| 26 | + next[l] = head[b]; |
| 27 | + head[b] = l; |
| 28 | + flow[l] = 0; |
| 29 | + cost[l] = -c; |
| 30 | +} |
| 31 | + |
| 32 | +int spfa (int n, int s, int t) { |
| 33 | + int i, l, r; |
| 34 | + for (i = 0; i < n; ++ i) |
| 35 | + d[i] = inf, v[i] = 0; |
| 36 | + d[q[l = 0] = s] = 0; |
| 37 | + r = 1; |
| 38 | + while (l ^ r) { |
| 39 | + int x = q[l ++]; |
| 40 | + l &= 65535; |
| 41 | + v[x] = 0; |
| 42 | + for (i = head[x]; i; i = next[i]) { |
| 43 | + int y = vpt[i]; |
| 44 | + if (flow[i] > 0 && d[x] + cost[i] < d[y]) { |
| 45 | + d[y] = d[x] + cost[i]; |
| 46 | + pre[y] = x; |
| 47 | + preh[y] = i; |
| 48 | + if (!v[y]) |
| 49 | + q[r ++] = y, v[y] = 1, r &= 65535; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + return d[t]; |
| 54 | +} |
| 55 | + |
| 56 | +int mincostmaxflow (int n, int s, int t, int &f_ans) { |
| 57 | + int ans = 0, i, f; |
| 58 | + f_ans = 0; |
| 59 | + while (true) { |
| 60 | + f = spfa(n, s, t); |
| 61 | + if (f == inf) |
| 62 | + break; |
| 63 | + ans += f; |
| 64 | + f = inf; |
| 65 | + for (i = t; i != s; i = pre[i]) |
| 66 | + f = min(f, flow[preh[i]]); |
| 67 | + f_ans += f; |
| 68 | + for (i = t; i != s; i = pre[i]) |
| 69 | + flow[preh[i]] -= f, flow[preh[i] ^ 1] += f; |
| 70 | + } |
| 71 | + return ans; |
| 72 | +} |
| 73 | + |
| 74 | +void init (int n) { |
| 75 | + l = 1; |
| 76 | + int i; |
| 77 | + for (i = 0; i < n; ++ i) |
| 78 | + head[i] = 0; |
| 79 | +} |
| 80 | + |
| 81 | +int main () { |
| 82 | + int i, j, t, m, n, u, v, r, s, a, b, c; |
| 83 | + while (scanf("%d%d", &n, &m) != EOF) { |
| 84 | + init(n + 2); |
| 85 | + add(0, 1, 2, 0); |
| 86 | + add(n, n + 1, 2, 0); |
| 87 | + while (m --) { |
| 88 | + scanf("%d%d%d", &a, &b, &c); |
| 89 | + add(a, b, 1, c); |
| 90 | + add(b, a, 1, c); |
| 91 | + } |
| 92 | + s = mincostmaxflow(n + 2, 0, n + 1, t); |
| 93 | + printf("%d\n", s); |
| 94 | + } |
| 95 | + return 0; |
| 96 | +} |
0 commit comments