网络流模板

using ll = long long;

const int MAXN = 205, MAXM = 5005;

template<typename __T>
struct network {
  struct Edge {
    int v, nxt;
    __T cap, flow;
  }e[2 * MAXM];

  int n, S, T, head[MAXN], tot = -1, dep[MAXN], cur[MAXN];
  __T maxflow = 0;

  void init(int N) {
    fill(head + 1, head + N + 1, -1), n = N, tot = -1;
  }

  void addedge(int u, int v, __T w) {
    e[++tot] = {v, head[u], w, 0}, head[u] = tot;
    e[++tot] = {u, head[v], 0, 0}, head[v] = tot;
  }

  bool bfs() {
    queue<int> que;
    fill(dep + 1, dep + n + 1, 0);
    dep[S] = 1;
    que.push(S);
    while(!que.empty()) {
      int u = que.front();
      que.pop();
      for(int i = head[u]; ~i; i = e[i].nxt) {
        int v = e[i].v;
        if(!dep[v] && e[i].cap > e[i].flow) {
          dep[v] = dep[u] + 1;
          que.push(v);
        }
      }
    }
    return dep[T];
  }

  __T dfs(int u, __T flow) {
    if(u == T || !flow) {
      return flow;
    }
    __T ret = 0;
    for(int &i = cur[u]; ~i; i = e[i].nxt) {
      int v = e[i].v;
      __T d;
      if(dep[v] == dep[u] + 1 && (d = dfs(v, min(flow - ret, e[i].cap - e[i].flow)))) {
        ret += d, e[i].flow += d, e[i ^ 1].flow -= d;
        if(ret == flow) {
          return ret;
        }
      }
    }
    return ret;
  }

  void dinic() {
    maxflow = 0;
    for(int i = 0; i <= tot; ++i) {
      e[i].flow = 0;
    }
    while(bfs()) {
      for(int i = 1; i <= n; ++i) {
        cur[i] = head[i];
      }
      maxflow += dfs(S, numeric_limits<__T>::max());
    }
  }
};

network<ll> G;
posted @ 2025-12-13 08:57  Yaosicheng124  阅读(2)  评论(0)    收藏  举报