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
| #include <iostream> #include <cstdio> #include <queue> #include <cstring> #define INF 0x7fffffff using namespace std; struct node {int v, c, nxt;} E[12000005]; int n, m, pre[1000005], d[1000005], cnt; void init() {cnt = 0, memset(pre, -1, sizeof(pre));} void insert(int u, int v, int c) { E[cnt].v = v, E[cnt].c = c, E[cnt].nxt = pre[u], pre[u] = cnt++; E[cnt].v = u, E[cnt].c = 0, E[cnt].nxt = pre[v], pre[v] = cnt++; } bool BFS() { memset(d, -1, sizeof(d)); queue <int> que; que.push(1), d[1] = 0; while (!que.empty()) { int u = que.front(); que.pop(); for (int i = pre[u]; ~i; i = E[i].nxt) { int v = E[i].v, c = E[i].c; if (~d[v] || !c) continue; d[v] = d[u]+1, que.push(v); } } return d[n*m] != -1; } int DFS(int u, int flow) { if (u == n*m) return flow; int ret = 0; for (int i = pre[u]; ~i; i = E[i].nxt) { int v = E[i].v, c = E[i].c; if (d[u]+1 != d[v] || !c) continue; int tmp = DFS(v, min(flow, c)); flow -= tmp, ret += tmp, E[i].c -= tmp, E[i^1].c += tmp; if (!flow) break; } if (!ret) d[u] = -1; return ret; } int Dinic() {int ret = 0; while (BFS()) ret += DFS(1, INF); return ret;} int main() { scanf("%d%d", &n, &m), init(); for (int i = 1; i <= n; i++) for (int j = 1, x; j < m; j++) scanf("%d", &x), insert(m*(i-1)+j, m*(i-1)+j+1, x), insert(m*(i-1)+j+1, m*(i-1)+j, x); for (int i = 1; i < n; i++) for (int j = 1, x; j <= m; j++) scanf("%d", &x), insert(m*(i-1)+j, m*i+j, x), insert(m*i+j, m*(i-1)+j, x); for (int i = 1; i < n; i++) for (int j = 1, x; j < m; j++) scanf("%d", &x), insert(m*(i-1)+j, m*i+j+1, x), insert(m*i+j+1, m*(i-1)+j, x); printf("%d", Dinic()); return 0; }
|