二元费用模型基本题hhhh,以前一直以为这个题和happiness是一个。。。
#include<bits/stdc++.h> #define ll long long #define pb push_back const int maxn=30005; const int inf=1<<30; using namespace std; vector<int> g[maxn]; struct lines{ int to,flow,cap; }l[maxn*73]; int t=-1,S,T,d[maxn],cur[maxn]; bool v[maxn]; inline void add(int from,int to,int cap){ l[++t]=(lines){to,0,cap},g[from].pb(t); l[++t]=(lines){from,0,0},g[to].pb(t); } inline bool BFS(){ queue<int> q; memset(v,0,sizeof(v)); q.push(S),v[S]=1,d[S]=0; int x; lines e; while(!q.empty()){ x=q.front(),q.pop(); for(int i=g[x].size()-1;i>=0;i--){ e=l[g[x][i]]; if(e.flow<e.cap&&!v[e.to]){ v[e.to]=1,d[e.to]=d[x]+1; q.push(e.to); } } } return v[T]; } int dfs(int x,int A){ if(x==T||!A) return A; int flow=0,f,sz=g[x].size(); for(int &i=cur[x];i<sz;i++){ lines &e=l[g[x][i]]; if(d[x]==d[e.to]-1&&(f=dfs(e.to,min(e.cap-e.flow,A)))){ A-=f,flow+=f; e.flow+=f,l[g[x][i]^1].flow-=f; if(!A) break; } } return flow; } inline int max_flow(){ int an=0; while(BFS()){ memset(cur,0,sizeof(cur)); an+=dfs(S,1<<30); } return an; } int n,m,ID[105][105],cnt,now,ans; int main(){ scanf("%d%d",&n,&m),S=0,T=1,cnt=1; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) ID[i][j]=++cnt; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%d",&now),add(S,ID[i][j],now),ans+=now; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%d",&now),add(ID[i][j],T,now),ans+=now; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){ scanf("%d",&now),add(S,++cnt,now),ans+=now; add(cnt,ID[i][j],inf); if(ID[i-1][j]) add(cnt,ID[i-1][j],inf); if(ID[i+1][j]) add(cnt,ID[i+1][j],inf); if(ID[i][j-1]) add(cnt,ID[i][j-1],inf); if(ID[i][j+1]) add(cnt,ID[i][j+1],inf); } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){ scanf("%d",&now),add(++cnt,T,now),ans+=now; add(ID[i][j],cnt,inf); if(ID[i-1][j]) add(ID[i-1][j],cnt,inf); if(ID[i+1][j]) add(ID[i+1][j],cnt,inf); if(ID[i][j-1]) add(ID[i][j-1],cnt,inf); if(ID[i][j+1]) add(ID[i][j+1],cnt,inf); } printf("%d ",ans-max_flow()); return 0; }