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 112 113 114 115
| #include <iostream> #include <cstdio> #include <queue> #include <climits> #define inf INT_MAX using namespace std; const int N = 260, M = 2e3 + 10; bool vis[N]; int n, m, st, ed, d[N], pre[N], incf[N]; int idx = -1, hd[N], nxt[M], edg[M], wt[M], f[M]; bool spfa() { for (int i = 0; i <= ed; i++) d[i] = -inf; for (int i = 0; i <= ed; i++) incf[i] = 0; d[st] = 0; queue <int> q; q.push(st); vis[st] = true; incf[st] = inf; while (!q.empty()) { int t = q.front(); q.pop(); vis[t] = false; for (int i = hd[t]; ~i; i = nxt[i]) if (wt[i] && d[t] + f[i] > d[edg[i]]) { d[edg[i]] = d[t] + f[i]; pre[edg[i]] = i; incf[edg[i]] = min(incf[t], wt[i]); if (!vis[edg[i]]) { q.push(edg[i]); vis[edg[i]] = false; } } } return incf[ed] > 0; } int ek() { int res = 0; while (spfa()) { int t = incf[ed]; res += d[ed] * incf[ed]; for (int i = ed; i != st; i = edg[pre[i] ^ 1]) { wt[pre[i]] -= t; wt[pre[i] ^ 1] += t; } } return res; } void add(int a, int b, int c, int d) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; f[idx] = d; } int num(int x, int y) { return x * (m + 1) + y; } int main() { int ns, nt; cin >> ns >> nt >> n >> m; st = num(n, m) + 1; ed = st + 1; for (int i = 0; i <= ed; i++) hd[i] = -1; for (int i = 0, a; i <= n; i++) for (int j = 0; j < m; j++) { int t = num(i, j), h = num(i, j + 1); cin >> a; add(t, h, 1, a); add(h, t, 0, -a); add(t, h, inf, 0); add(h, t, 0, 0); } for (int j = 0, a; j <= m; j++) for (int i = 0; i < n; i++) { int t = num(i, j), h = num(i + 1, j); cin >> a; add(t, h, 1, a); add(h, t, 0, -a); add(t, h, inf, 0); add(h, t, 0, 0); } for (int i = 1, a, b, c; i <= ns; i++) { cin >> a >> b >> c; int t = num(b, c); add(st, t, a, 0); add(t, st, 0, 0); } for (int i = 1, a, b, c; i <= nt; i++) { cin >> a >> b >> c; int t = num(b, c); add(t, ed, a, 0); add(ed, t, 0, 0); } cout << ek(); return 0; }
|