- 通过建图使其满足题目约束条件
Code
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
using namespace std;
const int inf=1e9;
const int N=1e5;
const int M=1e5;
struct node{int y,n,v,w;}e[M];
int lin[M],D[N],incf[N],pre[N],d[N],v[N],maxflow=0,ans=0,len=1,x,s,S,T,n,m;
void read(int x,int y,int v,int w)
{e[++len].y=y,e[len].n=lin[x],e[len].v=v,e[len].w=w,lin[x]=len;}
void add(int x,int y,int v,int w)
{read(x,y,v,w);read(y,x,0,-w);}
bool SPFA(int S,int T){
memset(v,0,sizeof(v));
memset(d,0x3f,sizeof(d));
queue<int> q;
q.push(S),d[S]=0,incf[S]=inf,v[S]=1;
while(q.size()){
int x=q.front();q.pop();v[x]=0;
for(int i=lin[x];i;i=e[i].n){
int y=e[i].y;
if(!e[i].v)continue;
if(d[y]>d[x]+e[i].w){
pre[y]=i;
d[y]=d[x]+e[i].w;
incf[y]=min(incf[x],e[i].v);
if(!v[y])v[y]=1,q.push(y);
}
}
}
if(d[T]>1e9)return 0;
return 1;
}
void upd(int S,int T){
int x=T;
while(x!=S){
int i=pre[x];
e[i].v-=incf[T];
e[i^1].v+=incf[T];
x=e[i^1].y;
}
maxflow+=incf[T];
ans+=d[T]*incf[T];
}
int main()
{
scanf("%d%d",&n,&m);s=2*n+1,S=s+1,T=S+1;
add(S,s,m,0);
rep(i,1,n){scanf("%d",&x);add(s,i,inf,0);D[i+n]+=x,D[i]-=x;}
rep(i,1,n)rep(j,i+1,n){scanf("%d",&x);if(x!=-1)add(i+n,j,inf,x);}
rep(i,1,n*2)if(D[i]>0)add(S,i,D[i],0);else add(i,T,-D[i],0);
while(SPFA(S,T))upd(S,T);
printf("%d",ans);
return 0;
}