【Loj116】有源汇有上下界最大流(网络流)

【Loj116】有源汇有上下界最大流(网络流)

题面

Loj

题解

模板题。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define ll long long
#define RG register
#define inf 1e9
#define MAX 500
#define MAXL 50000
inline int read()
{
    RG int x=0,t=1;RG char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-')t=-1,ch=getchar();
    while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
    return x*t;
}
struct Line{int v,next,w;}e[MAXL];
int h[MAX],cnt=2;
inline void Add(int u,int v,int w)
{
	e[cnt]=(Line){v,h[u],w};h[u]=cnt++;
	e[cnt]=(Line){u,h[v],0};h[v]=cnt++;
}
int level[MAX],cur[MAX];
bool bfs(int S,int T)
{
	memset(level,0,sizeof(level));level[S]=1;
	queue<int> Q;Q.push(S);
	while(!Q.empty())
	{
		int u=Q.front();Q.pop();
		for(int i=h[u];i;i=e[i].next)
			if(e[i].w&&!level[e[i].v])
				level[e[i].v]=level[u]+1,Q.push(e[i].v);
	}
	return level[T];
}
int dfs(int u,int T,int flow)
{
	if(u==T||!flow)return flow;
	int ret=0;
	for(int &i=cur[u];i;i=e[i].next)
	{
		int v=e[i].v,d;
		if(e[i].w&&level[v]==level[u]+1)
		{
			d=dfs(v,T,min(flow,e[i].w));
			ret+=d;flow-=d;
			e[i].w-=d;e[i^1].w+=d;
			if(!flow)break;
		}
	}
	return ret;
}
int Dinic(int S,int T)
{
	int ret=0;
	while(bfs(S,T))
	{
		memcpy(cur,h,sizeof(cur));
		ret+=dfs(S,T,inf);
	}
	return ret;
}
void Fail(){puts("please go home to sleep");}
int n,m,S,T,SS,TT,M[MAX],ans,rb;
int main()
{
	n=read();m=read();S=read();T=read();
	SS=0;TT=n+1;
	for(int i=1;i<=m;++i)
	{
		int u=read(),v=read(),B=read(),C=read();
		Add(u,v,C-B);M[u]-=B;M[v]+=B;
	}
	for(int i=1;i<=n;++i)
		if(M[i]>=0)Add(SS,i,M[i]);
		else Add(i,TT,-M[i]);
	Add(T,S,inf);rb=cnt-1;Dinic(SS,TT);
	for(int i=h[SS];i;i=e[i].next)if(e[i].w){Fail();return 0;}
	h[T]=e[h[T]].next;h[S]=e[h[S]].next;
	ans+=Dinic(S,T);ans+=e[rb].w;
	printf("%d\n",ans);
	return 0;
}

posted @ 2018-07-09 21:15  小蒟蒻yyb  阅读(864)  评论(0编辑  收藏  举报