LOJ #116 有源汇点有上下界的最大流

先连一条从汇点到源点的容量为INF的边,将其转化成无源汇点有上下界的可行流,判断是否可行
若可行的话删掉超级源点和超级汇点,再跑一遍最大流即可



#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstdlib>
using namespace std;
const int MAXM=30005,MAXN=250;
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;
}
queue <int> q;
int n,m,s,t,ss,tt,maxflow,head[MAXN],dep[MAXN],cur[MAXN],nume;
struct edge{
	int to,nxt,cap,flow;
}e[MAXM<<1];
void adde(int from,int to,int cap){
	e[++nume].to=to;
	e[nume].cap=cap;
	e[nume].nxt=head[from];
	head[from]=nume;
}
bool bfs(int s,int t){
	memset(dep,0,sizeof(dep));
	q.push(s);dep[s]=1;
	while(!q.empty()){
		int u=q.front();q.pop();
		for(int i=head[u];i;i=e[i].nxt){
			int v=e[i].to;
			if(s!=ss&&v==ss) continue;
			if(s!=ss&&v==tt) continue;
			if(!dep[v]&&e[i].flow<e[i].cap){
				dep[v]=dep[u]+1;
				q.push(v);
			}
		}
	}
	return dep[t];
}
int dfs(int u,int flow,int t){
	if(u==t) return flow;
	int tot=0;
	for(int &i=cur[u];i&&tot<flow;i=e[i].nxt){
		int v=e[i].to;
		if(dep[v]==dep[u]+1&&e[i].flow<e[i].cap){
			if(int temp=dfs(v,min(flow-tot,e[i].cap-e[i].flow),t)){
				e[i].flow+=temp;
				e[((i-1)^1)+1].flow-=temp;
				tot+=temp;
			}
		}
	}
	return tot;
}
void dinic(int s,int t){
	while(bfs(s,t)){
		for(int i=1;i<=n+2;i++) cur[i]=head[i];
		maxflow+=dfs(s,0x3f3f3f3f,t);
	}
}
int main(){
	n=init();m=init();s=init();t=init();
	ss=n+1;tt=n+2;
	int tot=0;
	for(int i=1;i<=m;i++){
		int u=init(),v=init(),c=init(),d=init();
		adde(u,v,d-c);
		adde(v,u,0);
		adde(u,tt,c);
		adde(tt,u,0);
		adde(ss,v,c);
		adde(v,ss,0);
		tot+=c;
	}
	adde(t,s,0x3f3f3f3f);
	dinic(ss,tt);
	if(maxflow<tot){
		printf("please go home to sleep\n");
	}else{
		dinic(s,t);
		maxflow=0;
		for(int i=head[s];i;i=e[i].nxt) maxflow+=e[i].flow;
		cout<<maxflow<<endl;
	}
	return 0;
}
posted @ 2018-01-20 11:01  Mr_Wolfram  阅读(158)  评论(0编辑  收藏  举报