Luogu 3381(最小费用流)

传送门

模板题。最小费用最大流,要求同时输出最大流以及最小费用,复杂度有点玄学,每增广一次,下一次SPFA的复杂度又会降低。所以这种题暂时只能这么处理:看出来有后效性的相互约束关系的就考虑用费用流解决。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int N=5004,M=50004,INF=0x3f3f3f3f;
int n,m,source,sink;
int head[N],etot=0,dis[N],pre[N];
bool inq[N];
struct EDGE {
	int u,v,nxt,c,r;
}e[M<<1];
inline int read() {
	int x=0;char c=getchar();
	while (c<'0'||c>'9') c=getchar();
	while (c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar();
	return x;
}
inline void adde(int u,int v,int r,int c) {
	e[etot].nxt=head[u],e[etot].u=u,e[etot].v=v,e[etot].r=r,e[etot].c=c,head[u]=etot++;
	e[etot].nxt=head[v],e[etot].u=v,e[etot].v=u,e[etot].r=0,e[etot].c=-c,head[v]=etot++;
}
inline bool SPFA() {
	queue<int > q;
	memset(dis,INF,sizeof(dis));
	memset(inq,false,sizeof(inq));
	pre[source]=-1,dis[source]=0,inq[source]=true;
	q.push(source);
	while (!q.empty()) {
		int p=q.front();
		q.pop();
		inq[p]=false;
		for (int i=head[p];~i;i=e[i].nxt) {
			int v=e[i].v;
			if (e[i].r>0&&dis[v]>dis[p]+e[i].c) {
				dis[v]=dis[p]+e[i].c;
				pre[v]=i;
				if (!inq[v]) q.push(v),inq[v]=true;
			}
		}
	}
	return dis[sink]^INF;
}
inline void MCMF() {
	int maxflow=0,mincost=0;
	while (SPFA()) {
		int temp=INF;
		for (int i=pre[sink];~i;i=pre[e[i].u]) temp=min(temp,e[i].r);
		maxflow+=temp,mincost+=temp*dis[sink];
		for (int i=pre[sink];~i;i=pre[e[i].u]) e[i].r-=temp,e[i^1].r+=temp;
	}
	printf("%d %d\n",maxflow,mincost);
}
int main() {
//	freopen("P3381.in","r",stdin);
	memset(head,-1,sizeof(head));
	n=read(),m=read(),source=read(),sink=read();
	for (register int i=0;i<m;++i) {
		int u=read(),v=read(),r=read(),c=read();
		adde(u,v,r,c);
	}
	MCMF();
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值