【Loj117】有源汇上下界最小流(网络流)

时间:2021-06-22 15:39:35

【Loj117】有源汇上下界最小流(网络流)

题面

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 1e18
#define MAX 60000
#define MAXL 500000
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;ll w;}e[MAXL];
int h[MAX],cnt=2;
inline void Add(int u,int v,ll 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];
}
ll dfs(int u,int T,ll flow)
{
if(u==T||!flow)return flow;
ll ret=0;
for(int &i=cur[u];i;i=e[i].next)
{
int v=e[i].v;ll 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;
}
ll Dinic(int S,int T)
{
ll 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(T,S);ans+=e[rb].w;
printf("%d\n",ans);
return 0;
}