/* I will wait for you */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define make(a,b) make_pair(a,b) #define fi first #define se second using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair PII; const int maxn=1010; const int maxm=1010; const int maxs=26; const int INF=1<<29; const int P=1000000007; const double error=1e-9; struct edge{ int v,a,next; }e[maxn]; int s,t,p,ans,cnt,head[maxn],dis[maxn],cur[maxn],q[maxn]; int dx[5]={0,0,0,1,-1},dy[5]={0,1,-1,0,0}; void insert(int u,int v,int a) { e[cnt]=(edge){v,a,head[u]},head[u]=cnt++; e[cnt]=(edge){u,0,head[v]},head[v]=cnt++; } int bfs() { for(int i=1;i<=t;i++) dis[i]=-1; int he=0,ta=1;q[0]=s,dis[s]=0; while(he!=ta) { int u=q[he++]; for(int i=head[u],v;i!=-1;i=e[i].next) if(e[i].a&&dis[v=e[i].v]==-1) dis[v]=dis[u]+1,q[ta++]=v; } return dis[t]!=-1; } int dfs(int u,int a) { if(u==t) return a; int flow=0,f; for(int i=cur[u],v;a&&i!=-1;i=e[i].next) { if(e[i].a&&dis[v=e[i].v]==dis[u]+1&&(f=dfs(v,min(a,e[i].a)))>0) { e[i].a-=f,e[i^1].a+=f,a-=f,flow+=f; if(e[i].a) cur[u]=i; } } if(!flow) dis[u]=-1; return flow; } void dinic() { while(bfs()) memcpy(cur,head,sizeof(cur)),ans-=dfs(s,INF); } int main() { int n,m;scanf("%d%d",&n,&m); p=n*m,s=3*p+1,t=3*p+2; memset(head,-1,sizeof(head)); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { int c;scanf("%d",&c);ans+=c; insert(s,(i-1)*m+j,c); } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { int c;scanf("%d",&c);ans+=c; insert((i-1)*m+j,t,c); } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { int c;scanf("%d",&c);ans+=c; for(int k=0;k<5;k++) { int nx=i+dx[k],ny=j+dy[k]; if(nx>=1&&nx<=n&&ny>=1&&ny<=m) insert((i-1)*m+j+p,(nx-1)*m+ny,INF); } insert(s,(i-1)*m+j+p,c); } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { int c;scanf("%d",&c);ans+=c; for(int k=0;k<5;k++) { int nx=i+dx[k],ny=j+dy[k]; if(nx>=1&&nx<=n&&ny>=1&&ny<=m) insert((nx-1)*m+ny,(i-1)*m+j+2*p,INF); } insert((i-1)*m+j+2*p,t,c); } dinic();printf("%d\n",ans); return 0; }