跳到正文

题解

P14580 【模板】有源汇上下界最小流 题解

_Dolphin_约 4 分钟
原文

这是 2025年12月25日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年12月24日
收录
2025年12月25日
更新
2026年11月8日
篇幅
约 4 分钟
获赞
15
题目
P14580

版本

  1. v2当前
  2. v1

引流旧模板题题解:link

Code
C++
#include<bits/stdc++.h>
#define afor(i,x,y) for(int i=(x);i<=(y);i++)
#define bfor(i,x,y) for(int i=(x);i>=(y);i--)
using namespace std;
typedef long long ll;
const int N=1e6+10,M=1e6+10;
struct net{
    int tot,maxflow,head[N],cur[N],dep[N],to[M],nxt[M];
    int cap[M],flow[M];
    bool vis[N];
    void clear() {tot=-1,memset(head,-1,sizeof head);}
    void _add(int x,int y,int z) {
        to[++tot]=y,cap[tot]=z,flow[tot]=0;
        nxt[tot]=head[x],head[x]=tot;
    }
    void add(int x,int y,int z) {_add(x,y,z),_add(y,x,0);}
} g;
bool bfs(int s,int t) {
    memset(g.dep,0,sizeof g.dep);
    queue<int> q;
    q.push(s),g.dep[s]=1;
    while(!q.empty()) {
        int x=q.front();
        q.pop();
        for(int i=g.head[x];~i;i=g.nxt[i]) {
            int y=g.to[i];
            if(!g.dep[y]&&g.flow[i]<g.cap[i])
                q.push(y),g.dep[y]=g.dep[x]+1;
        }
    }
    return g.dep[t];
}
int dfs(int x,int t,int now) {
    if(x==t) return now;
    int res=0;
    g.vis[x]=1;
    for(int i=g.cur[x];~i&&res<now;i=g.nxt[i]) {
        g.cur[x]=i;
        int y=g.to[i];
        if(!g.vis[y]&&g.dep[y]==g.dep[x]+1&&g.flow[i]<g.cap[i]) {
            int d=dfs(y,t,min(now-res,g.cap[i]-g.flow[i]));
            res+=d,g.flow[i]+=d,g.flow[i^1]-=d;
        }
    }
    g.vis[x]=0;
    return res;
}
int dinic(int s,int t) {
    g.maxflow=0;
    while(bfs(s,t)) {
        memcpy(g.cur,g.head,sizeof g.cur);
        g.maxflow+=dfs(s,t,1e9);
    }
    return g.maxflow;
}
int n,m,s,t,id,sum,d[N];
int main() {
    g.clear();
    scanf("%d%d%d%d",&n,&m,&s,&t);
    int S=n+1,T=n+2;
    afor(i,1,m) {
        int x,y,l,r;
        scanf("%d%d%d%d",&x,&y,&l,&r);
        g.add(x,y,r-l);
        d[x]+=l,d[y]-=l;
    }
    g.add(t,s,1e9),id=g.tot^1;
    afor(i,1,n) {
        if(d[i]>0) g.add(i,T,d[i]),sum+=d[i];
        if(d[i]<0) g.add(S,i,-d[i]);
    }
    if(dinic(S,T)!=sum) return printf("N"),0;
    int ans=g.flow[id];
    g.flow[id]=g.flow[id^1]=g.cap[id]=0;
    ans-=dinic(t,s);
    printf("%d",ans);
    return 0;
}