题目:https://www.luogu.org/problemnew/show/P4014
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; typedef long long ll; const int N=205,cN=20405; const ll INF=0x7fffffff; int n,head[N],incf[N],pre[N],xnt=1,t; ll dis[N],ans; bool in[N]; struct Edge{ int next,from,to,cap; ll w; Edge(int n=0,int f=0,int t=0,int c=0,ll w=0):next(n),from(f),to(t),cap(c),w(w) {} }edge[cN],tmp[cN]; bool spfa() { queue<int> q; memset(dis,-2,sizeof dis); q.push(0);in[0]=1; dis[0]=0;incf[0]=INF;pre[t]=0; while(q.size()) { int k=q.front();q.pop();in[k]=0; for(int i=head[k],v;i;i=edge[i].next) if(edge[i].cap&&dis[k]+edge[i].w>dis[v=edge[i].to]) { dis[v]=dis[k]+edge[i].w; incf[v]=min(edge[i].cap,incf[k]); pre[v]=i; // printf("v=%d pre[v]=%d ",v,pre[v]); if(!in[v])q.push(v),in[v]=1; } } return pre[t]; } bool spfa1() { queue<int> q; memset(dis,1,sizeof dis); q.push(0);in[0]=1; dis[0]=0;incf[0]=INF;pre[t]=0; while(q.size()) { int k=q.front();q.pop();in[k]=0; for(int i=head[k],v;i;i=tmp[i].next) if(tmp[i].cap&&dis[k]+tmp[i].w<dis[v=tmp[i].to]) { dis[v]=dis[k]+tmp[i].w; incf[v]=min(tmp[i].cap,incf[k]); pre[v]=i; // printf("v=%d pre[v]=%d ",v,pre[v]); if(!in[v])q.push(v),in[v]=1; } } return pre[t]; } void ek() { for(int k=pre[t];k;k=pre[edge[k].from]) { // printf("(%d)",edge[k].to); edge[k].cap-=incf[t]; edge[k^1].cap+=incf[t]; ans+=edge[k].w*incf[t]; } } void ek1() { for(int k=pre[t];k;k=pre[tmp[k].from]) { // printf("(%d)",edge[k].to); tmp[k].cap-=incf[t]; tmp[k^1].cap+=incf[t]; ans+=tmp[k].w*incf[t]; } } int main() { scanf("%d",&n); ll x;t=2*n+1; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { scanf("%lld",&x); edge[++xnt]=Edge(head[i],i,j+n,1,x);head[i]=xnt; edge[++xnt]=Edge(head[j+n],j+n,i,0,-x);head[j+n]=xnt; } for(int i=1;i<=n;i++) { edge[++xnt]=Edge(head[0],0,i,1,0);head[0]=xnt; edge[++xnt]=Edge(head[i],i,0,0,0);head[i]=xnt; edge[++xnt]=Edge(head[i+n],i+n,t,1,0);head[i+n]=xnt; edge[++xnt]=Edge(head[t],t,i+n,0,0);head[t]=xnt; } memcpy(tmp,edge,sizeof edge); while(spfa1()) ek1(); printf("%lld ",ans); ans=0; while(spfa()) ek(); printf("%lld",ans); return 0; }