Codeforces 708D 费用流 (呃我们的考试题)
NB的题目背景
输入输出一样
考试的时候貌似只有gzz一个人搞出来了
%gzz
思路:
分情况讨论
add(x,y,C,E) C是费用 E是流量
1. f>c add(x,y,2,inf),add(y,x,0,f-c),add(y,x,1,c),ans+=f-c;
2. 否则add(x,y,1,c-f),add(x,y,2,inf),add(y,x,1,f);
因为原图中源汇流量不守恒 add(n,1,0,inf)
//By SiriusRen
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 6666
#define M 666666
#define inf 0x3f3f3f3f
#define mem(x,y) memset(x,y,sizeof(x))
int n,m,xx,yy,cc,ff,ans,edge[M],cost[M],v[M],nxt[M],first[N],tot,vis[N],minn[N],d[N],with[N];
void Add(int x,int y,int C,int E){edge[tot]=E,cost[tot]=C,v[tot]=y,nxt[tot]=first[x],first[x]=tot++;}
void add(int x,int y,int C,int E){Add(x,y,C,E),Add(y,x,-C,0);}
bool tell(){
mem(vis,0),mem(with,0),mem(d,0x3f),mem(minn,0x3f);
queue<int>q;q.push(0),d[0]=0;
while(!q.empty()){
int t=q.front();q.pop();vis[t]=0;
for(int i=first[t];~i;i=nxt[i])
if(d[v[i]]>d[t]+cost[i]&&edge[i]){
with[v[i]]=i,d[v[i]]=d[t]+cost[i],minn[v[i]]=min(minn[t],edge[i]);
if(!vis[v[i]])vis[v[i]]=1,q.push(v[i]);
}
}return d[n]!=0x3f3f3f3f;
}
int zeng(){
for(int i=n;i;i=v[with[i]^1])
edge[with[i]]-=minn[n],edge[with[i]^1]+=minn[n];
return minn[n]*d[n];
}
int main(){
mem(first,-1),scanf("%d%d",&n,&m);
while(m--){
scanf("%d%d%d%d",&xx,&yy,&cc,&ff);
d[yy]+=ff,d[xx]-=ff;
if(ff>=cc)add(xx,yy,2,inf),add(yy,xx,0,ff-cc),add(yy,xx,1,cc),ans+=ff-cc;
else add(xx,yy,1,cc-ff),add(xx,yy,2,inf),add(yy,xx,1,ff);
}
add(n,1,0,inf),n++;
for(int i=1;i<n;i++)if(d[i]>0)add(0,i,0,d[i]);else add(i,n,0,-d[i]);
while(tell())ans+=zeng();
printf("%d\n",ans);
}