网络流24题之一,拆点加拆边。洛谷上有许多题解,这里就不班门弄斧啦。
#include<iostream> #include<cstdio> #include<queue> #include<cstring> using namespace std; const int N=5000+10; const int M=50000+10; const int INF=0x3f3f3f3f; int n,m,s,t,A,B,bs,maxflow,mincost; struct edge{ int nxt,to,cap,cost; }edges[M<<1]; int cnt=1,head[N],pre[N]; void add_edge(int x,int y,int z,int c) { edges[++cnt].nxt=head[x]; edges[cnt].to=y; edges[cnt].cap=z; edges[cnt].cost=c; head[x]=cnt; } queue<int> q; int dis[N],lim[N]; bool inq[N]; bool spfa(int s,int t) { while (!q.empty()) q.pop(); memset(dis,0x3f,sizeof(dis)); memset(inq,0,sizeof(inq)); dis[s]=0; inq[s]=1; lim[s]=INF; q.push(s); while (!q.empty()) { int x=q.front(); q.pop(); for (int i=head[x];i;i=edges[i].nxt) { edge e=edges[i]; if (e.cap && dis[x]+e.cost<dis[e.to]) { dis[e.to]=dis[x]+e.cost; pre[e.to]=i; //即e.to这个点是从i这条边来的 lim[e.to]=min(lim[x],e.cap); if (!inq[e.to]) { q.push(e.to); inq[e.to]=1; } } } inq[x]=0; } return !(dis[t]==INF); } void MCMF() { maxflow=0; mincost=0; while (spfa(s,t)) { int now=t; maxflow+=lim[t]; mincost+=lim[t]*dis[t]; while (now!=s) { edges[pre[now]].cap-=lim[t]; edges[pre[now]^1].cap+=lim[t]; now=edges[pre[now]^1].to; } } } int id(int x,int y) { return (x-1)*m+y; } int main() { scanf("%d%d%d%d",&A,&B,&n,&m); n++; m++; s=0; t=2*n*m+1; bs=n*m; for (int i=1;i<=n;i++) { for (int j=1;j<m;j++) { int x; scanf("%d",&x); add_edge(id(i,j)+bs,id(i,j+1),1,-x); add_edge(id(i,j+1),id(i,j)+bs,0,x); add_edge(id(i,j)+bs,id(i,j+1),INF,0); add_edge(id(i,j+1),id(i,j)+bs,0,0); } } for (int j=1;j<=m;j++) { for (int i=1;i<n;i++) { int x; scanf("%d",&x); add_edge(id(i,j)+bs,id(i+1,j),1,-x); add_edge(id(i+1,j),id(i,j)+bs,0,x); add_edge(id(i,j)+bs,id(i+1,j),INF,0); add_edge(id(i+1,j),id(i,j)+bs,0,0); } } for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) add_edge(id(i,j),id(i,j)+bs,INF,0),add_edge(id(i,j)+bs,id(i,j),0,0); for (int i=1;i<=A;i++) { int k,x,y; scanf("%d%d%d",&k,&x,&y); x++; y++; add_edge(s,id(x,y),k,0); add_edge(id(x,y),s,0,0); } for (int i=1;i<=B;i++) { int k,x,y; scanf("%d%d%d",&k,&x,&y); x++; y++; add_edge(id(x,y)+bs,t,k,0); add_edge(t,id(x,y)+bs,0,0); } MCMF(); cout<<-mincost<<endl; return 0; }