最小割。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> #define maxv 1050 #define maxn 550 #define maxe 2000050 #define inf 1000000007 using namespace std; int n,b[maxn][maxn],c[maxn],s,t,g[maxv],nume=1,sum=0,dis[maxv],tot[maxv]; struct edge { int v,f,nxt; }e[maxe]; queue <int> q; void addedge(int u,int v,int f) { e[++nume].v=v;e[nume].f=f;e[nume].nxt=g[u];g[u]=nume; e[++nume].v=u;e[nume].f=0;e[nume].nxt=g[v];g[v]=nume; } void build() { for (int i=1;i<=n;i++) { addedge(s,i,tot[i]);addedge(i,i+n,inf); addedge(i+n,t,c[i]); } for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) addedge(i+n,j,b[i][j]); } bool bfs() { for (int i=s;i<=t;i++) dis[i]=inf; dis[s]=0;q.push(s); while (!q.empty()) { int head=q.front();q.pop(); for (int i=g[head];i;i=e[i].nxt) { int v=e[i].v; if (dis[v]>dis[head]+1 && e[i].f>0) { dis[v]=dis[head]+1; q.push(v); } } } return dis[t]!=inf; } int dinic(int x,int low) { if (x==t) return low; int ret=0; for (int i=g[x];i && low;i=e[i].nxt) { int v=e[i].v; if (e[i].f>0 && dis[v]==dis[x]+1) { int dd=dinic(v,min(low,e[i].f)); low-=dd;ret+=dd;e[i].f-=dd;e[i^1].f+=dd; } } if (!ret) dis[x]=inf; return ret; } int main() { scanf("%d",&n);s=0;t=2*n+1; for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) { scanf("%d",&b[i][j]); {sum+=b[i][j];tot[i]+=b[i][j];} } for (int i=1;i<=n;i++) {scanf("%d",&c[i]);} build(); while (bfs()) sum-=dinic(s,inf); printf("%d\n",sum); return 0; }