bzoj1974 network 网络扩容 网络流

       第一问跑一个最大流就好了。对于第二问,在残余网络上连边。如果u->v有边,则连边容量inf,费用为扩容的费用。最后再新建一个汇点T,从n->T连一条容量为K,费用为0的边以限制容量。然后跑最小费用最大流即可。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#define inf 1000000000
#define N 40005
using namespace std;

int n,m,gol,tot=1,addflow,fst[N],pnt[N],len[N],cst[N],nxt[N];
int d[N],h[N],u[N],v[N],w[N],e[N],last[N]; bool vis[N];
bool bfs(){
	memset(d,-1,sizeof(d)); d[1]=1;
	int head=0,tail=1; h[1]=1;
	while (head<tail){
		int x=h[++head],p;
		for (p=fst[x]; p; p=nxt[p]) if (len[p]){
			int y=pnt[p];
			if (d[y]==-1){ d[y]=d[x]+1; h[++tail]=y; }
		}
	}
	return d[gol]!=-1;
}
int dfs(int x,int rst){
	if (x==gol || !rst) return rst; int flow=0,p;
	for (p=fst[x]; p; p=nxt[p]) if (len[p]){
		int y=pnt[p]; if (d[x]+1!=d[y]) continue;
		int tmp=dfs(y,min(rst,len[p])); if (!tmp) continue;
		flow+=tmp; len[p]-=tmp;
		len[p^1]+=tmp; rst-=tmp; if (!rst) break;
	}
	if (!flow) d[x]=-1; return flow;
}
void add(int aa,int bb,int cc,int dd){
	pnt[++tot]=bb; len[tot]=cc; cst[tot]=dd; nxt[tot]=fst[aa]; fst[aa]=tot;
}
bool spfa(){
	int head=0,tail=1,i; d[1]=0; h[1]=1;
	for (i=2; i<=gol; i++) d[i]=inf;
	while (head!=tail){
		head=head%20000+1;
		int x=h[head],p; vis[x]=0;
		for (p=fst[x]; p; p=nxt[p]) if (len[p]){
			int y=pnt[p];
			if (d[x]+cst[p]<d[y]){
				d[y]=d[x]+cst[p]; last[y]=p;
				if (!vis[y]){ vis[y]=1; tail=tail%20000+1; h[tail]=y; }
			}
		}
	}
	return d[gol]!=inf;
}
int updata(){
	int tmp=inf,sum=0,i;
	for (i=gol; i!=1; i=pnt[last[i]^1]) tmp=min(tmp,len[last[i]]);
	for (i=gol; i!=1; i=pnt[last[i]^1]){
		sum+=tmp*cst[last[i]];
		len[last[i]]-=tmp; len[last[i]^1]+=tmp;
		
	}
	return sum;
}
int main(){
	scanf("%d%d%d",&n,&m,&addflow); int i;
	for (i=1; i<=m; i++){
		scanf("%d%d%d%d",&u[i],&v[i],&w[i],&e[i]);
		add(u[i],v[i],w[i],0); add(v[i],u[i],0,0);
	}
	int ans=0; gol=n; while (bfs()) ans+=dfs(1,inf); printf("%d ",ans);
	for (i=1; i<=m; i++){
		add(u[i],v[i],inf,e[i]); add(v[i],u[i],0,-e[i]);
	}
	ans=0; gol=n+1; add(n,n+1,addflow,0); add(n+1,n,0,0);
	while (spfa()) ans+=updata(); printf("%d\n",ans);
	return 0;
}


by lych

2016.2.25

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值