题目描述
题解
原图:
对于pi,拆点xi,yi
s->S,[m,m],0
S->xi,[0,inf],0
yi->t,[0,inf],0
xi->yi,[vi,vi],0
对于有航线的pi和pj,yi->xj,[0,inf],cost
这样就建好了原图
那么有源汇有上下界的费用流的改造方法:
首先建立附加源汇ss,tt
对于原图里有的一条边x->y,[l,r],cost,变成x->y,r-l,cost
每一个点的权di定义为所有流入这个点的边的下界和-所有流出这个点的边的下界和
对于一个点i,若di>0,ss->i,di,0;若di<0,i->tt,-di,0
连边t->s,inf,0
然后对ss,tt做最小费用最大流
最终的费用为(网络流中计算的费用+原图中有费用的边的下界*这条边的费用)
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
#define N 40005
#define inf 2000000000
int n,m,x,mincost,s,t,S,ss,tt;
int tot,point[N],nxt[N],v[N],remain[N],c[N];
int dis[N],last[N],d[N];
bool vis[N];
queue <int> q;
void addedge(int x,int y,int cap,int z)
{
++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=cap; c[tot]=z;
++tot; nxt[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0; c[tot]=-z;
}
int addflow(int s,int t)
{
int now=t,ans=inf;
while (now!=s)
{
ans=min(ans,remain[last[now]]);
now=v[last[now]^1];
}
now=t;
while (now!=s)
{
remain[last[now]]-=ans;
remain[last[now]^1]+=ans;
now=v[last[now]^1];
}
return ans;
}
bool spfa(int s,int t)
{
memset(dis,127,sizeof(dis));dis[s]=0;
memset(vis,0,sizeof(vis));vis[s]=1;
while (!q.empty()) q.pop();q.push(s);
while (!q.empty())
{
int now=q.front();q.pop();
vis[now]=0;
for (int i=point[now];i!=-1;i=nxt[i])
if (dis[v[i]]>dis[now]+c[i]&&remain[i])
{
dis[v[i]]=dis[now]+c[i];
last[v[i]]=i;
if (!vis[v[i]])
{
vis[v[i]]=1;
q.push(v[i]);
}
}
}
if (dis[t]>inf) return 0;
int flow=addflow(s,t);
mincost+=flow*dis[t];
return 1;
}
int main()
{
tot=-1;memset(point,-1,sizeof(point));
scanf("%d%d",&n,&m);
S=n+n+1,s=S+1,t=s+1;ss=t+1,tt=ss+1;
d[s]-=m,d[S]+=m;
for (int i=1;i<=n;++i)
{
scanf("%d",&x);
addedge(S,i,inf,0);
addedge(n+i,t,inf,0);
d[i]-=x,d[n+i]+=x;
}
for (int i=1;i<n;++i)
for (int j=i+1;j<=n;++j)
{
scanf("%d",&x);
if (x==-1) continue;
addedge(n+i,j,inf,x);
}
for (int i=1;i<=t;++i)
{
if (d[i]>0) addedge(ss,i,d[i],0);
if (d[i]<0) addedge(i,tt,-d[i],0);
}
addedge(t,s,inf,0);
while (spfa(ss,tt));
printf("%d\n",mincost);
}