Dinic 无用点优化求调

P3376 【模板】网络最大流

d0j1a_1701 @ 2023-11-03 22:24:37

注意第 39 行加了 "NEEDFIX" 注释的无用点优化。

如果 dfs 时向一个点推流却发现返回的流量是 0,那说明那个点无剩余流量(增广完毕),应该被舍弃。但加上那一行会导致 TLE,哪里写假了?

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
/* d0j1a_1701 FastIO ver. 5.0 */
/* 省略快读代码 */
int beg[210], nxt[10010], to[10010], cur[210], tot = -1;
int n, m, s, t, id[210][210], dep[210];
long long val[10010];
inline void add(int u, int v, long long w) {
    nxt[++tot] = beg[u], beg[u] = tot, val[tot] = w, to[tot] = v;
    nxt[++tot] = beg[v], beg[v] = tot, val[tot] = 0, to[tot] = u;
}
inline bool bfs() {
    queue<int> q;
    memset(dep, -1, sizeof(dep));
    q.emplace(s), dep[s] = 0, cur[s] = beg[s];
    while(q.size()) {
        int u = q.front();
        q.pop();
        for(int i = beg[u]; ~i; i = nxt[i])
            if(val[i] && dep[to[i]] < 0) {
                int v = to[i];
                dep[v] = dep[u] + 1;
                cur[v] = beg[v];
                q.emplace(v);
                if(v == t)  return 1;
            }
    }
    return 0;
}
long long dfs(int u, long long rest = 1e18) {
    if(u == t)  return rest;
    long long flow = 0;
    for(int i = cur[u]; ~i; i = nxt[i])
        if(dep[to[i]] == dep[u] + 1) {
            int v = to[i];
            auto f = dfs(v, min(rest, val[i]));
            //if(!f)    dep[v] = -1; // NEEDFIX: 无用点优化
            val[i] -= f, val[i ^ 1] += f;
            flow += f, rest -= f;
            if(rest <= 0)   return flow; // 当前弧优化(推送量用尽)
        }
    return flow;
}
int main() {
    memset(beg, -1, sizeof(beg));
    io.read(n, m, s, t);
    for(int i = 1, u, v, w; i <= m; i++) {
        io.read(u, v, w);
        if(id[u][v])    val[id[u][v]] += w;
        else add(u, v, w), id[u][v] = tot - 1;
    }
    long long res = 0;
    while(bfs())    res += dfs(s);
    io.writeln(res);
    //system("pause");
    return 0;
}

by Nuisdete @ 2023-11-03 22:39:40

@d0j1a_1701 dfs 里面也得判边是否有剩余容量,加上就不 T 了。


by Nuisdete @ 2023-11-03 22:42:19

另外您这个当前弧优化是不是不太对啊,不是应该更新下 cur[u] 吗。


by d0j1a_1701 @ 2023-11-03 22:42:33

@louis_11 谢谢。AC 了。


|