#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #define N 6000666 using namespace std; const int inf=(1 << 26); int n,m,S,T,d; int idx,head[N],cur[N],q[N]; int e[N],ne[N],w[N]; int ans; int sum; inline void add(int u,int v,int f) { e[idx]=v; w[idx]=f; ne[idx]=head[u]; head[u]=idx++; e[idx]=u; w[idx]=f; ne[idx]=head[v]; head[v]=idx++; } inline bool bfs() { int f=0,t=0; memset(cur,-1,sizeof(cur)); q[t++]=S; cur[S]=0; while(f<t) { int now=q[f++]; for(int i=head[now]; ~i; i=ne[i]) { int v=e[i]; if(cur[v]==-1&&w[i]) { cur[v]=cur[now]+1; q[t++]=v; } } } if(cur[T]!=-1) return 1; return 0; } inline int dfs(int x,int f) { if(x==T) return f; int w1,used=0; for(int i=head[x]; ~i; i=ne[i]) { int v=e[i]; if(cur[v]==cur[x]+1&&w[i]) { w1=dfs(v,min(f-used,w[i])); // if(!w1) // { // cur[v]=-1; // continue; // } w[i]-=w1; w[i^1]+=w1; used+=w1; if(used==f) return f; } } if(!used) cur[x]=-1; return used; } void dinic() { while(bfs()) ans+=dfs(S,0x3f3f3f3f); } int gethash(int i, int j) { return (i - 1) * m + j; } int main() { memset(head,-1,sizeof head); cin>>n>>m; S=1,T=gethash(n, m); int tmp; for(int i = 1; i <= n; ++i) { for(int j = 1; j < m; ++j) cin>>tmp,add(gethash(i, j), gethash(i, j + 1), tmp); } for(int i = 1; i < n; ++i) { for(int j = 1; j <= m; ++j) cin>>tmp, add(gethash(i, j), gethash(i + 1, j), tmp); } for(int i = 1; i < n; ++i) { for(int j = 1; j < m; ++j) cin>>tmp,add(gethash(i, j), gethash(i + 1, j + 1), tmp); } dinic(); cout<<ans<<endl; return 0; }