多源汇最大流(最大流)

题意

给定一个包含(n)个点(m)条边的有向图,并给定每条边的容量,边的容量非负。

其中有(Sc)个源点,(Tc)个汇点。

图中可能存在重边和自环。

求整个网络的最大流。

思路

建立虚拟源点(S),分别向源点连容量是(infty)的边(正无穷的原因是不能让其成为流量的限制)

建立虚拟汇点(T),汇点分别向(T)连容量是(infty)的边(正无穷的原因是不能让其成为流量的限制)

跑最大流

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 10010, M = (N + 100000) * 2, inf = 1e8;

int n, m, S, T;
int h[N], e[M], f[M], ne[M], idx;
int cur[N], d[N];

void add(int a, int b, int c)
{
    e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx ++;
    e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx ++;
}

bool bfs()
{
    memset(d, -1, sizeof(d));
    queue<int> que;
    que.push(S);
    d[S] = 0, cur[S] = h[S];
    while(que.size()) {
        int t = que.front();
        que.pop();
        for(int i = h[t]; ~i; i = ne[i]) {
            int ver = e[i];
            if(d[ver] == -1 && f[i]) {
                d[ver] = d[t] + 1;
                cur[ver] = h[ver];
                if(ver == T) return true;
                que.push(ver);
            }
        }
    }
    return false;
}

int find(int u, int limit)
{
    int flow = 0;
    if(u == T) return limit;
    for(int i = cur[u]; ~i && flow < limit; i = ne[i]) {
        cur[u] = i;
        int ver = e[i];
        if(d[ver] == d[u] + 1 && f[i]) {
            int t = find(ver, min(f[i], limit - flow));
            if(!T) d[ver] = -1;
            f[i] -= t, f[i ^ 1] += t, flow += t;
        }
    }

    return flow;
}

int dinic()
{
    int res = 0, flow;
    while(bfs()) {
        while(flow = find(S, inf)) {
            res += flow;
        }
    }
    return res;
}

int main()
{
    int sc, tc;
    scanf("%d%d%d%d", &n, &m, &sc, &tc);
    memset(h, -1, sizeof(h));
    S = 0, T = n + 1;
    for(int i = 0; i < sc; i ++) {
        int x;
        scanf("%d", &x);
        add(S, x, inf);
    }
    for(int i = 0; i < tc; i ++) {
        int x;
        scanf("%d", &x);
        add(x, T, inf);
    }
    for(int i = 0; i < m; i ++) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }
    printf("%d
", dinic());
    return 0;
}
原文地址:https://www.cnblogs.com/miraclepbc/p/14402890.html