1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| const int MAXV=1e6+10,MAXE=4e6+10,MAXN=1e3+10; const int INF=0x3f3f3f3f; int N,M,S,T; struct Net { int next,to,val; }Edge[MAXE<<1]; int Head[MAXV],Cur[MAXV],Total=1; inline void addEdge(int u,int v,int w) { Edge[++Total]=(Net){Head[u],v,w};Head[u]=Total; Edge[++Total]=(Net){Head[v],u,0};Head[v]=Total; } int Fl[MAXV]; inline bool Bfs() { memset(Fl,-1,sizeof(Fl)); std::queue<int>Q; Q.push(S),Fl[S]=0,Cur[S]=Head[S]; while(!Q.empty()) { int u=Q.front();Q.pop(); for(int e=Head[u],v;e;e=Edge[e].next) { v=Edge[e].to; if(Fl[v]==-1&&Edge[e].val) { Fl[v]=Fl[u]+1,Cur[v]=Head[v]; if(v==T) return 1; Q.push(v); } } } return 0; } int Dfs(int x,int inf) { if(x==T) return inf; int flow=0; for(int e=Cur[x],v;e&&flow<inf;e=Edge[e].next) { v=Edge[e].to,Cur[x]=e; if(Fl[v]==Fl[x]+1&&Edge[e].val) { int k=Dfs(v,std::min(inf-flow,Edge[e].val)); if(!k) Fl[v]=-1; Edge[e].val-=k,Edge[e^1].val+=k,flow+=k; } } return flow; } inline int Dinic() { int r=0,flow; while(Bfs()) while(flow=Dfs(S,INF)) r+=flow; return r; } inline int getId(int x,int y) { return M*(x-1)+y; } int main() { read(N,M); S=0,T=N*M+1; addEdge(S,getId(1,1),INF),addEdge(getId(N,M),T,INF); for(int i=1;i<=N;++i) for(int j=1,x;j<M;++j) { read(x); addEdge(getId(i,j),getId(i,j+1),x); addEdge(getId(i,j+1),getId(i,j),x); } for(int i=1;i<N;++i) for(int j=1,x;j<=M;++j) { read(x); addEdge(getId(i,j),getId(i+1,j),x); addEdge(getId(i+1,j),getId(i,j),x); } for(int i=1;i<N;++i) for(int j=1,x;j<M;++j) { read(x); addEdge(getId(i,j),getId(i+1,j+1),x); addEdge(getId(i+1,j+1),getId(i,j),x); } write(Dinic()); return 0; }
|