跳到正文

个人记录

Flow 板子

Yu_Chengxuan约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年5月24日
收录
2026年5月29日
更新
2026年11月9日
篇幅
约 3 分钟

版本

  1. v1当前
C++
struct Flow {
  int node, T, head[N], cur[N], tot = 1;
  ll rev[N << 1];
  struct edge {
    int to, nxt;
    ll val;
  } G[N << 1];
  inline void add(int u, int v, ll w) {
    tot++, G[tot] = {v, head[u], w}, head[u] = tot;
    tot++, G[tot] = {u, head[v], 0}, head[v] = tot;    
  }
  bool bfs(int s) {
    for (int i = 0; i <= node; i++) rev[i] = inf;
    queue<int> q;
    q.push(s), rev[s] = 0;
    while (!q.empty()) {
      int u = q.front();
      q.pop();
      for (int e = head[u]; e; e = G[e].nxt) {
        int v = G[e].to; ll w = G[e].val;
        if (w > 0 && rev[v] == inf) {
          q.push(v), rev[v] = rev[u] + 1;
          if (v == T) return 1;
        } 
      }
    }
    return 0;
  }
  ll dfs(int u, ll flow) {
    if (u == T) return flow;
    ll res = flow;
    for (int e = cur[u]; e && res; e = G[e].nxt) {
      cur[u] = e;
      int v = G[e].to; ll w = G[e].val;
      if (w && (rev[v] == rev[u] + 1)) {
        ll up = dfs(v, min(w, res));
        G[e].val -= up, G[e ^ 1].val += up;
        res -= up;
      }
    }
    return flow - res;
  }
  inline ll dinic(int s, int t) {
    T = t;
    ll flow = 0, ans = 0;
    while (bfs(s)) {
      for (int i = 0; i <= node; i++) cur[i] = head[i];
      while (flow = dfs(s, inf)) ans += flow;
    }
    return ans;
  }
} e, g;
原文