您的位置:首页 > 其它

[BZOJ3876][Ahoi2014]支线剧情(有源汇有上下界的费用流)

2017-02-05 16:26 639 查看

题目描述

传送门

注意这道题是要求每一条边都被覆盖,而不是每一个点

题解

原图的建图方法:

s->1,[0,inf],0

i->t,[0,inf],0

对于给出的一条边i->j费用为c,连边i->j,[1,inf],c

然后将这个图进行改造求有源汇有上下界的费用流即可

但是这道题让我迷惑的一点是,

原图如果是求最小费用最大流的话最大流不应该是inf么

大概是因为有源汇有上下界的费用流只是在满足流量上下界限制的情况下费用最小吧…不一定是最大流

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
#define N 310
#define E 20005
#define inf 2000000000

int n,k,goal,cost,s,t,ss,tt,mincost;
int tot,point
,nxt[E],v[E],remain[E],c[E];
int dis
,last
,d
;
bool vis
;
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",&n);
s=n+1,t=s+1,ss=t+1,tt=ss+1;
for (int i=1;i<=n;++i)
{
scanf("%d",&k);
while (k--)
{
scanf("%d%d",&goal,&cost);
--d[i];++d[goal];
addedge(i,goal,inf,cost);
}
}
k=tot;
addedge(s,1,inf,0);
for (int i=1;i<=n;++i) addedge(i,t,inf,0);
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));
for (int i=0;i<=k;i+=2)
mincost+=c[i];
printf("%d\n",mincost);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: