首页 > 学院 > 开发设计 > 正文

[BZOJ4108][Wf2015]Catering(有源汇有上下界的费用流)

2019-11-14 08:44:21
字体:
来源:转载
供稿:网友

题目描述

传送门

题解

原图的建图方法: 将2-n+1拆点xi,yi s->1,[0,k],0 1->xi,[0,inf],0 yi->t,[0,inf],0 xi->yi,[1,1],0 对于给出的费用,若i->j的费用为c yi->xj,[0,inf],c

然后将原图进行改造求最小费用最大流即可

代码

#include<algorithm>#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<queue>using namespace std;#define inf 2000000000#define N 210#define E 30005int n,k,x,s,t,ss,tt,mincost;int tot,point[N],nxt[E],v[E],remain[E],c[E];int d[N],dis[N],last[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,&k); s=1,t=n+n+3,ss=t+1,tt=ss+1; for (int i=1;i<=n;++i) for (int j=i+1;j<=n+1;++j) { scanf("%d",&x); addedge(1+n+i,j,inf,x); } addedge(s,1+n+1,k,0); for (int i=2;i<=n+1;++i) { --d[i],++d[1+n+i]; addedge(1+n+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)); PRintf("%d/n",mincost);}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表