写了一发费用流
Part5:
有上下界的费用流。
我们可以转化到有源汇上下界可行流的建图,然后跑费用流。
#include<iostream>
#include<cstdio>
#include<cstring>
#define inf 1000000007
#define N 205
#define M 205
#define E 25005
using namespace std;
int n,m,s,SS,TT,cnt=1,ans;
int head[N],dis[N],q[N],path[N];
bool vis[N];
int next[E],list[E],cost[E],from[E],flow[E];
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline void insert(int x,int y,int z,int w)
{
next[++cnt]=head[x];
head[x]=cnt;
from[cnt]=x;
list[cnt]=y;
flow[cnt]=z;
cost[cnt]=w;
}
inline bool spfa()
{
for (int i=0;i<=TT;i++) dis[i]=inf;
int t=0,w=1,x;
q[1]=SS; dis[SS]=0; vis[SS]=1;
while (t!=w)
{
t=(t+1)%M;
x=q[t];
for (int i=head[x];i;i=next[i])
if (flow[i]&&dis[list[i]]>dis[x]+cost[i])
{
dis[list[i]]=dis[x]+cost[i];
path[list[i]]=i;
if (!vis[list[i]])
{
vis[list[i]]=1;
w=(w+1)%M;
q[w]=list[i];
}
}
vis[x]=0;
}
return dis[TT]!=inf;
}
inline void mcf()
{
int x=inf;
for (int i=path[TT];i;i=path[from[i]]) x=min(x,flow[i]);
for (int i=path[TT];i;i=path[from[i]])
flow[i]-=x,flow[i^1]+=x,ans+=x*cost[i];
}
int main()
{
n=read(); m=read(); s=0; SS=n<<1|1; TT=SS+1;
for (int i=1;i<=n;i++)
{
int x=read();
insert(i,TT,x,0); insert(TT,i,0,0);
insert(SS,i+n,x,0); insert(i+n,SS,0,0);
insert(s,i,inf,0); insert(i,s,0,0);
}
for (int i=1;i<=n;i++)
for (int j=i+1;j<=n;j++)
{
int x=read();
if (x!=-1) insert(i+n,j,inf,x),insert(j,i+n,0,-x);
}
insert(SS,s,m,0);
while (spfa()) mcf();
cout << ans << endl;
return 0;
}