# [BZOJ2127] happiness

2 3
1534 2296 345
551 1429 4085
1488 2707 3095
1198 3778 1811
3571 4832 1658
2894 2742 1118
1690 2112
1279 4179
466 3002
3977 4256

## 样例输出 SampleOutput

32532

BZOJ 2127

``````#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define id(x,y) ((x-1)*m+y)
const int inf = 0x7fffffff;
const int maxn = 105 * 105;
const int maxm = maxn * 30;
const int dx[5] = {0, 0, 0, 1, -1};
const int dy[5] = {0, 1, -1, 0, 0};//R,L,D,U
int i, j, t, n, m, l, r, k, z, y, x;
struct edge
{
int to, fl, nx;
} e[maxm];
int cnt, num, ans;
int a[105][105][5];
deque <int> q;
inline void ins(int u, int v, int f)
{
e[cnt] = (edge)
{
e[cnt] = (edge)
{
}
inline bool bfs(int s, int t, int tim)
{
int i, u, v;
while (!q.empty()) q.pop_front();
dis[s] = 0; used[s] = tim;
q.push_back(s);
while (!q.empty())
{
u = q.front(); q.pop_front();
for (i = head[u]; i != -1; i = e[i].nx)
{
v = e[i].to;
if (used[v] != tim && e[i].fl > 0)
{
used[v] = tim;
dis[v] = dis[u] + 1;
q.push_back(v);
}
}
}
return (used[t] == tim);
}
int dfs(int u, int t, int flow)
{
int v, d, f = flow;
if (u == t) return flow;
for (int &i = cur[u]; i != -1 && f > 0; i = e[i].nx)
{
v = e[i].to;
if (dis[v] == dis[u] + 1 && e[i].fl > 0)
{
d = dfs(v, t, min(f, e[i].fl));
e[i].fl -= d; e[i ^ 1].fl += d;
f -= d;
}
}
return flow - f;
}
inline void dinic(int s, int t)
{
while (bfs(s, t, ++num))
{
ans -= dfs(s, t, inf);
}
printf("%d\n", ans >> 1);
}
int main()
{
cnt = num = ans = 0;
scanf("%d%d", &n, &m);
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
{
scanf("%d", &x);
x <<= 1;
ans += x;
ins(0, id(i, j), x);
}
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
{
scanf("%d", &x);
x <<= 1;
ans += x;
ins(id(i, j), n * m + 1, x);
}
for (i = 1; i < n; i++)
for (j = 1; j <= m; j++)
{
scanf("%d", &x);
ans += x << 1;
ins(0, id(i, j), x);
ins(0, id(i + 1, j), x);
a[i][j][3] = a[i + 1][j][4] += x;
}
for (i = 1; i < n; i++)
for (j = 1; j <= m; j++)
{
scanf("%d", &x);
ans += x << 1;
ins(id(i, j), n * m + 1, x);
ins(id(i + 1, j), n * m + 1, x);
a[i][j][3] = a[i + 1][j][4] += x;
}
for (i = 1; i <= n; i++)
for (j = 1; j < m; j++)
{
scanf("%d", &x);
ans += x << 1;
ins(0, id(i, j), x);
ins(0, id(i, j + 1), x);
a[i][j][1] = a[i][j + 1][2] += x;
}
for (i = 1; i <= n; i++)
for (j = 1; j < m; j++)
{
scanf("%d", &x);
ans += x << 1;
ins(id(i, j), n * m + 1, x);
ins(id(i, j + 1), n * m + 1 , x);
a[i][j][1] = a[i][j + 1][2] += x;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
for (k = 1; k <= 4; k++)
{
x = i + dx[k]; y = j + dy[k];
if (x > 0 && x <= n && y > 0 && y <= m) ins(id(i, j), id(x, y), a[i][j][k]);
}
dinic(0, n * m + 1);
return 0;
}``````