问题描述
$ n $ 个点,$ m $ 条边,每条边 $ e $ 有一个流量下界 $ \text{lower}(e) $ 和流量上界 $ \text{upper}(e) $,求一种可行方案使得在所有点满足流量平衡条件的前提下,所有边满足流量限制。
https://www.luogu.com.cn/blog/duyi/qian-tan-you-shang-xia-jie-di-wang-lao-liu
\(\mathrm{Code}\)
#include<bits/stdc++.h>
using namespace std;
const int maxn=220;
const int maxm=500007;
const int INF=0x3f3f3f3f;
int n,m,S,T;
int Head[maxn],to[maxm],Next[maxm],w[maxm],tot=1;
int Getin[maxn],Sendout[maxn];
int Low[maxm];
void addedge(int x,int y,int z){
to[++tot]=y,Next[tot]=Head[x],Head[x]=tot,w[tot]=z;
}
void add(int x,int y,int z){
addedge(x,y,z);addedge(y,x,0);
}
int d[maxn];
bool bfs(void){
memset(d,0,sizeof(d));
queue<int>q;q.push(S);d[S]=1;
while(!q.empty()){
int x=q.front();q.pop();
for(int i=Head[x];i;i=Next[i]){
int y=to[i];
if(d[y]||!w[i]) continue;
d[y]=d[x]+1;q.push(y);
if(y==T) return true;
}
}
return false;
}
int dfs(int x,int flow){
if(x==T) return flow;
int rest=flow;
for(int i=Head[x];i;i=Next[i]){
int y=to[i];
if(d[y]!=d[x]+1||!w[i]) continue;
int k=dfs(y,min(rest,w[i]));
if(!k) d[y]=0;
else w[i]-=k,w[i^1]+=k,rest-=k;
}
return flow-rest;
}
int MaxFlow;
void Dinic(void){
int t;
while(bfs()){
while(t=dfs(S,INF)) MaxFlow+=t;
}
}
void Init(void){
scanf("%d%d",&n,&m);
for(int i=1,x,y,low,upp;i<=m;i++){
scanf("%d%d%d%d",&x,&y,&low,&upp);
Getin[y]+=low,Sendout[x]+=low;
add(x,y,upp-low);Low[i]=low;
}
}
bool check(void){
for(int i=Head[S];i;i=Next[i]){
if(w[i]) return false;
}
return true;
}
void Work(void){
S=n+1,T=S+1;
for(int i=1;i<=n;i++){
int diff=Getin[i]-Sendout[i];
if(!diff) continue;
if(diff>0) add(S,i,diff);
else add(i,T,-diff);
}
Dinic();
if(!check()){
puts("NO");return;
}
puts("YES");
for(int i=2;i<=2*m+1;i+=2){
printf("%d\n",w[i^1]+Low[(i+1)/2]);
}
}
int main(){
Init();
Work();
return 0;
}