Dinic 46分求助(已看瞎)
查看原帖
Dinic 46分求助(已看瞎)
56545
盼君勿忘楼主2021/4/23 20:03
#include <iostream>
#include <cstring>
#include <climits>
#include <queue>
#define inf LLONG_MAX
using namespace std;
typedef long long ll;

const int maxn = 210, maxm = 10010;

inline int read() {
    int x = 0, flag = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') flag = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + ch - '0';
        ch = getchar();
    }
    return x * flag;
}

int n, m, s, t;

int head[maxn];
struct edge {
    int v, w, next;
} edges[maxm];

int cnt = -1;
void add_edge(int u, int v, int w) {
    edges[++cnt].v = v;
    edges[cnt].w = w;
    edges[cnt].next = head[u];
    head[u] = cnt;
}

int d[maxn];
bool bfs() {
    memset(d, -1, sizeof(d));
    queue<int> q; q.push(s);
    d[s] = 0;
    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (int i = head[u]; i != -1; i = edges[i].next) {
            edge& e = edges[i];
            if (d[e.v] != -1 || e.w <= 0) continue;
            q.push(e.v);
            d[e.v] = d[u] + 1;
        }
    }
    return d[t] != -1;
}

int cur[maxn];
ll dfs(int u, ll a) {
    if (u == t || a == 0) return a;
    int flow = 0, f = 0;
    for (int& i = cur[u]; i != -1; i = edges[i].next) {
        edge& e = edges[i];
        if (d[e.v] != d[u] + 1) continue;
        if (f = dfs(e.v, min(a, (ll)e.w)) > 0) {
            e.w -= f;
            edges[i ^ 1].w += f;
            flow += f; a -= f;
            if (a == 0) break;
        }
    }
    return flow;
}

inline ll Dinic() {
    ll flow = 0;
    while (bfs()) {
        memcpy(cur, head, sizeof(cur));
        flow += dfs(s, inf);
    }
    return flow;
}

int main() {
    memset(head, -1, sizeof(head));
    n = read(), m = read(), s = read(), t = read();
    for (int i = 0; i < m; i++) {
        int u = read(), v = read(), w = read();
        add_edge(u, v, w);
        add_edge(v, u, 0);
    }
    ll flow = Dinic(); 
    printf("%lld\n", flow);
    return 0;
}
2021/4/23 20:03
加载中...