Fancy大法好~~
#include<cstdio>
#include<queue>
using namespace std;
int n,m,S,T,ans,tot=1,v,ds[1000001];
int head[1000001],to[6000001],rest[6000001],next[6000001];
queue<int> Q;
struct N{
int to,ne,rest;
}e[6000005];
void add(int x,int y,int z)
{
tot++;
e[tot].to=y;
e[tot].ne=head[x];
e[tot].rest=z;
head[x]=tot;
tot++;
e[tot].to=x;
e[tot].ne=head[y];
e[tot].rest=z;
head[y]=tot;
//to[++tot]=y;rest[tot]=z;next[tot]=head[x];head[x]=tot;
//to[++tot]=x;rest[tot]=z;next[tot]=head[y];head[y]=tot;
}
bool Bfs()
{
for(int i=S;i<=T;i++) ds[i]=-1;
Q.push(S);ds[S]=0;
while(!Q.empty())
{
int x=Q.front(); Q.pop();
for(int i=head[x];i;i=e[i).ne)
if(e[i].rest&&ds[e[i].to]==-1)
ds[e[i].to]=ds[x]+1,Q.push(e[i].to);
}
return ds[T]>-1;
}
int Dfs(int x,int flow)
{
if(x==T) return flow;
int a=0,b;
for(int i=head[x];i;i=e[i].ne)
if(e[i].rest&&ds[e[i].to]==ds[x]+1)
{
b=Dfs(e[i].to,min(flow-a,e[i].rest));
e[i].rest-=b;e[i^1].rest+=b;
a+=b;
if(a==flow) return flow;
}
if(!a) ds[x]=-1;
return a;
}
int main()
{
scanf("%d%d",&n,&m);S=1;T=n*m;
for(int i=1;i<=n;i++)
for(int j=1;j<m;j++)
scanf("%d",&v),add((i-1)*m+j,(i-1)*m+j+1,v);
for(int i=1;i<n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&v),add((i-1)*m+j,i*m+j,v);
for(int i=1;i<n;i++)
for(int j=1;j<m;j++)
scanf("%d",&v),add((i-1)*m+j,i*m+j+1,v);
while(Bfs()) ans+=Dfs(S,0x7fffffff);
printf("%d",ans);
}