最小费用最大流模版

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN=5005,MAXM=50005;
int init(){
	int rv=0,fh=1;
	char c=getchar();
	while(c<'0'||c>'9'){
		if(c=='-') fh=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9'){
		rv=(rv<<1)+(rv<<3)+c-'0';
		c=getchar();
	}
	return fh*rv;
}
int n,m,nume,flow,head[MAXN],s,t,pre[MAXN],delta,dis[MAXN];
bool f[MAXN];
queue <int> q;
struct edge{
	int to,nxt,cap,flow,cost;
}e[MAXM<<1];
void adde(int from,int to,int cap,int cost){
	e[++nume].to=to;
	e[nume].cap=cap;
	e[nume].nxt=head[from];
	e[nume].cost=cost;
	head[from]=nume;
}
bool SPFA(){
	memset(dis,0x3f,sizeof(dis));
	memset(pre,0,sizeof(pre));
	q.push(s);f[s]=1;
	dis[s]=0;
	pre[s]=0;
	//for(int i=1;i<=n;i++) cout<<dis[i]<<endl;
	while(!q.empty()){
		int u=q.front();q.pop();
		f[u]=0;
		for(int i=head[u];i;i=e[i].nxt){
			int v=e[i].to;
			if((dis[v]>dis[u]+e[i].cost)&&(e[i].flow<e[i].cap)){
				dis[v]=dis[u]+e[i].cost;
				pre[v]=i;
				if(!f[v]){
					f[v]=1;
					q.push(v);
				}
			}
		}
	}
//	cout<<dis[t]<<endl;
	if(dis[t]!=0x3f3f3f3f) return 1;
	else return 0;
}
int mincost;
int main(){
	n=init();m=init();s=init();t=init();
	for(int i=1;i<=m;i++){
		int u=init(),v=init(),cap=init(),cost=init();
		adde(u,v,cap,cost);
		adde(v,u,0,-cost);
	}
	while(SPFA()){
		delta=0x3f3f3f3f;
		for(int i=pre[t];i;i=pre[e[((i-1)^1)+1].to]){
			delta=min(delta,e[i].cap-e[i].flow);
		}
		for(int i=pre[t];i;i=pre[e[((i-1)^1)+1].to]){
			e[i].flow+=delta;
			e[((i-1)^1)+1].flow-=delta;
			mincost+=e[i].cost*delta;
		}
		flow+=delta;
		//cout<<1<<endl;
	}
	printf("%d %d\n",flow,mincost);
	return 0;
}
posted @ 2018-01-19 09:34  Mr_Wolfram  阅读(103)  评论(0编辑  收藏  举报