1 /**************************************************************
2 Problem: 3894
3 User: Doggu
4 Language: C++
5 Result: Accepted
6 Time:2380 ms
7 Memory:19036 kb
8 ****************************************************************/
9
10 #include <cstdio>
11 #include <algorithm>
12 #include <cstring>
13 #include <queue>
14 #define pos(x,y) ((x-1)*m+y)
15 const int N = 200200;
16 const int M = 1001001;
17 const int dx[] = {0,1,-1,0,0};
18 const int dy[] = {0,0,0,1,-1};
19 struct Edge {int v,upre,cap,flow;}g[M];
20 int head[N], ne = 0;
21 inline void adde(int u,int v,int cap) {
22 g[ne]=(Edge){v,head[u],cap,0};head[u]=ne++;
23 g[ne]=(Edge){u,head[v],0,0};head[v]=ne++;
24 }
25 int n, m, s, t, x, sum, INF=0x3f3f3f3f;
26 int d[N];
27 bool vis[N];
28 std::queue<int> q;
29 bool BFS() {
30 memset(vis, 0, sizeof(vis));
31 while(!q.empty()) q.pop();
32 d[s]=0;vis[s]=1;q.push(s);
33 while(!q.empty()) {
34 int u=q.front();q.pop();
35 for( int i = head[u]; i != -1; i = g[i].upre ) {
36 int v=g[i].v;
37 if(!vis[v] && g[i].cap>g[i].flow) d[v]=d[u]+1,vis[v]=1,q.push(v);
38 }
39 }
40 return vis[t];
41 }
42 int cur[N];
43 int DFS(int u,int a) {
44 if(u == t||a == 0) return a;
45 int f, flow = 0;
46 for( int& i = cur[u]; i != -1; i = g[i].upre ) {
47 int v=g[i].v;
48 if(d[v]==d[u]+1&&(f=DFS(v,std::min(a,g[i].cap-g[i].flow)))>0) {
49 g[i].flow+=f;g[i^1].flow-=f;a-=f;flow+=f;
50 if(a==0) break;
51 }
52 }
53 return flow;
54 }
55 void maxflow() {
56 int flow = 0;
57 while(BFS()) {
58 memcpy(cur,head,sizeof(head));
59 flow+=DFS(s,INF);
60 }
61 printf("%d\n",sum-flow);
62 }
63 int main() {
64 memset(head,-1,sizeof(head));
65 scanf("%d%d",&n,&m);
66 s=0;t=32999;
67 for( int i = 1; i <= n; i++ ) for( int j = 1; j <= m; j++ ) {
68 scanf("%d",&x);sum+=x;adde(s,pos(i,j),x);
69 }
70 for( int i = 1; i <= n; i++ ) for( int j = 1; j <= m; j++ ) {
71 scanf("%d",&x);sum+=x;adde(pos(i,j),t,x);
72 }
73 for( int i = 1; i <= n; i++ ) for( int j = 1; j <= m; j++ ) {
74 scanf("%d",&x);sum+=x;adde(s,pos(n,m)+pos(i,j),x);
75 for( int d = 0; d <= 4; d++ ) if(1<=i+dx[d]&&i+dx[d]<=n&&1<=j+dy[d]&&j+dy[d]<=m) adde(pos(n,m)+pos(i,j),pos(i+dx[d],j+dy[d]),INF);
76 }
77 for( int i = 1; i <= n; i++ ) for( int j = 1; j <= m; j++ ) {
78 scanf("%d",&x);sum+=x;adde(2*pos(n,m)+pos(i,j),t,x);
79 for( int d = 0; d <= 4; d++ ) if(1<=i+dx[d]&&i+dx[d]<=n&&1<=j+dy[d]&&j+dy[d]<=m) adde(pos(i+dx[d],j+dy[d]),2*pos(n,m)+pos(i,j),INF);
80 }
81 maxflow();
82 return 0;
83 }
84