思路分析:
代码示例 :
const int maxn = 1e5+5;
const int inf = 0x3f3f3f3f;
int n, m;
struct node
{
    int to, next;
    int flow;
}e[maxn];
int head[maxn];
int cnt;
int s, t, sum;
void addedge(int u, int v, int w){
    e[cnt].to = v, e[cnt].flow = w, e[cnt].next = head[u], head[u] = cnt++;
    e[cnt].to = u, e[cnt].flow = 0, e[cnt].next = head[v], head[v] = cnt++;
}
int dep[500], que[500];
bool bfs(int s, int t){
    memset(dep, 0, sizeof(dep));
    dep[s] = 1; que[0] = s;
    int head1 = 0, tail = 1;
   
    while(head1 < tail) {
        int v = que[head1++];
        for(int i = head[v]; i != -1; i = e[i].next){
            int to = e[i].to;
            if (e[i].flow && !dep[to]) {
                dep[to] = dep[v]+1;
                que[tail++] = to;
            }
        }
    } 
    return dep[t];
}
int dfs(int u, int f1){
    if (u == t || f1 == 0) return f1;
    int f = 0;
    for(int i = head[u]; i != -1; i = e[i].next){
        int to = e[i].to;
        if (e[i].flow && dep[to] == dep[u]+1){
            int x = dfs(to, min(e[i].flow, f1));
            e[i].flow -= x, e[i^1].flow += x;
            f1 -= x, f += x;
            if (f1 == 0) return f;
        }
    }
    if (!f) dep[u] = -2;
    return f;
}
int id[15000], ans[15000];
void maxflow() {
    int res = 0;
    
    while(bfs(s, t)){
        res += dfs(s, inf);
    }
    if (res == sum) {
        printf("YES\n");
        for(int i = 1; i <= m; i++){
            printf("%d\n", e[id[i]].flow+ans[i]);
        }       
    } 
    else printf("NO\n");
}
int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    cin >> n >> m;
    int u, v, x, y;
    s = 0, t = n+1;
    memset(head, -1, sizeof(head)); 
    
    for(int i = 1; i <= m; i++){
        scanf("%d%d%d%d", &u, &v, &x, &y);
        addedge(u, v, y-x); 
        id[i] = cnt-1;
        addedge(s, v, x);
        addedge(u, t, x);      
        sum += x;   
        ans[i] = x; 
    }
    maxflow();
    return 0;
}
原文:https://www.cnblogs.com/ccut-ry/p/9939697.html