模板题
承接有源汇有上下界最大流说。
这个和有源汇有上下界最大流的思路是相同的,我们只需要求出一个可行流,考虑最多能退回去多少流,于是我们从\(ed\)向\(st\)跑一遍最大流,减去即可。
code(只改了最大流代码的一行):
#include<bits/stdc++.h>
using namespace std;
const int maxn=50010;
const int maxm=125010;
const int inf=1e9;
int n,m,cnt_edge=1,st,ed,S,T,sum,ans;
int head[maxn],cur[maxn],dep[maxn],in[maxn],out[maxn];
struct Edge{int u,v,down,up;}E[maxm];
struct edge{int to,nxt,flow;}e[(maxn+maxm)<<1];
inline int read()
{
char c=getchar();int res=0,f=1;
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9')res=res*10+c-'0',c=getchar();
return res*f;
}
inline void add(int u,int v,int w)
{
e[++cnt_edge].nxt=head[u];
head[u]=cnt_edge;
e[cnt_edge].to=v;
e[cnt_edge].flow=w;
}
inline void addflow(int u,int v,int w){add(u,v,w);add(v,u,0);}
inline bool bfs()
{
memset(dep,0,sizeof(dep));
for(int i=0;i<=n+1;i++)cur[i]=head[i];
queue<int>q;
q.push(S);dep[S]=1;
while(!q.empty())
{
int x=q.front();q.pop();
for(int i=head[x];i;i=e[i].nxt)
{
int y=e[i].to;
if(dep[y]||e[i].flow<=0)continue;
dep[y]=dep[x]+1;q.push(y);
}
}
return dep[T]>0;
}
int dfs(int x,int lim)
{
if(x==T||lim<=0)return lim;
int res=lim;
for(int i=cur[x];i;i=e[i].nxt)
{
cur[x]=i;
int y=e[i].to;
if(dep[y]!=dep[x]+1||e[i].flow<=0)continue;
int tmp=dfs(y,min(res,e[i].flow));
if(tmp<=0)dep[y]=0;
res-=tmp;
e[i].flow-=tmp,e[i^1].flow+=tmp;
if(res<=0)break;
}
return lim-res;
}
inline int Dinic(int x,int y)
{
S=x,T=y;
int res=0;
while(bfs())res+=dfs(S,inf);
return res;
}
int main()
{
n=read(),m=read(),st=read(),ed=read();
S=0,T=n+1;
for(int i=1;i<=m;i++)E[i].u=read(),E[i].v=read(),E[i].down=read(),E[i].up=read();
for(int i=1;i<=m;i++)addflow(E[i].u,E[i].v,E[i].up-E[i].down);
for(int i=1;i<=m;i++)in[E[i].v]+=E[i].down,out[E[i].u]+=E[i].down;
for(int i=1;i<=n;i++)
{
if(in[i]>=out[i])addflow(S,i,in[i]-out[i]),sum+=in[i]-out[i];
else addflow(i,T,out[i]-in[i]);
}
add(ed,st,inf);
if(Dinic(0,n+1)!=sum){puts("please go home to sleep");return 0;}
ans+=e[cnt_edge^1].flow;e[cnt_edge].flow=e[cnt_edge^1].flow=0;
for(int i=head[0];i;i=e[i].nxt)e[i].flow=e[i^1].flow=0;
for(int i=head[n+1];i;i=e[i].nxt)e[i].flow=e[i^1].flow=0;
ans-=Dinic(ed,st);//就这里改了一句。
printf("%d",ans);
return 0;
}