Skip to content

gomory_hu_tree.hpp

SECTIONGraph INCLUDEnoya/gomory_hu_tree.hpp

Gomory-Hu tree representing every pairwise minimum cut of an undirected nonnegative-capacity graph.

用 n-1 次最大流把无向图任意两点最小割编码成一棵树。

Implementation

View on GitHub

#ifndef NOYA_GOMORY_HU_TREE_HPP
#define NOYA_GOMORY_HU_TREE_HPP 1

/// @complexity Time: O(V) maximum-flow computations.
/// Space: O(V + E) plus the maximum-flow workspace.

#include "atcoder/maxflow.hpp"

#include <algorithm>
#include <cassert>
#include <limits>
#include <tuple>
#include <utility>
#include <vector>

namespace noya {

/// @brief Gomory-Hu tree representing every pairwise minimum cut of an
/// undirected nonnegative-capacity graph.
template <class Cap> struct gomory_hu_tree_result {
  std::vector<int> parent;
  std::vector<Cap> cut_value;
  std::vector<std::vector<std::pair<int, Cap>>> tree;

  /// @brief Return the minimum cut value between two vertices in O(n) time.
  Cap min_cut(int source, int sink) const {
    const int n = int(tree.size());
    assert(0 <= source && source < n);
    assert(0 <= sink && sink < n);
    if (source == sink) {
      return std::numeric_limits<Cap>::max();
    }
    std::vector<int> stack = {source};
    std::vector<int> previous(n, -1);
    std::vector<Cap> answer(n, std::numeric_limits<Cap>::max());
    previous[source] = source;
    while (!stack.empty()) {
      int vertex = stack.back();
      stack.pop_back();
      if (vertex == sink) {
        return answer[vertex];
      }
      for (auto [next, value] : tree[vertex]) {
        if (previous[next] == -1) {
          previous[next] = vertex;
          answer[next] = std::min(answer[vertex], value);
          stack.push_back(next);
        }
      }
    }
    assert(false);
    return Cap{};
  }
};

/// @brief Build a Gomory-Hu tree in O(n) maximum-flow computations. Each edge
/// is (u, v, capacity); parallel edges are supported and self-loops ignored.
template <class Cap>
gomory_hu_tree_result<Cap>
gomory_hu_tree(int n, const std::vector<std::tuple<int, int, Cap>> &edges) {
  assert(n >= 0);
  gomory_hu_tree_result<Cap> result;
  result.parent.assign(n, 0);
  result.cut_value.assign(n, Cap{});
  result.tree.resize(n);
  if (n <= 1) {
    return result;
  }

  for (const auto &[first, second, capacity] : edges) {
    assert(0 <= first && first < n);
    assert(0 <= second && second < n);
    assert(!(capacity < Cap{}));
  }

  for (int source = 1; source < n; source++) {
    int sink = result.parent[source];
    atcoder::mf_graph<Cap> graph(n);
    for (const auto &[first, second, capacity] : edges) {
      if (first == second || capacity == Cap{}) {
        continue;
      }
      graph.add_edge(first, second, capacity);
      graph.add_edge(second, first, capacity);
    }
    result.cut_value[source] = graph.flow(source, sink);
    std::vector<bool> side = graph.min_cut(source);
    for (int vertex = source + 1; vertex < n; vertex++) {
      if (result.parent[vertex] == sink && side[vertex]) {
        result.parent[vertex] = source;
      }
    }
    if (side[result.parent[sink]]) {
      result.parent[source] = result.parent[sink];
      result.parent[sink] = source;
      std::swap(result.cut_value[source], result.cut_value[sink]);
    }
  }

  for (int vertex = 1; vertex < n; vertex++) {
    int parent = result.parent[vertex];
    Cap value = result.cut_value[vertex];
    result.tree[vertex].emplace_back(parent, value);
    result.tree[parent].emplace_back(vertex, value);
  }
  return result;
}

} // namespace noya

#endif // NOYA_GOMORY_HU_TREE_HPP
#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <tuple>
#include <utility>
#include <vector>

/// @complexity Time: O(V) maximum-flow computations.
/// Space: O(V + E) plus the maximum-flow workspace.

namespace atcoder {

namespace internal {

template <class T> struct simple_queue {
    std::vector<T> payload;
    int pos = 0;
    void reserve(int n) { payload.reserve(n); }
    int size() const { return int(payload.size()) - pos; }
    bool empty() const { return pos == int(payload.size()); }
    void push(const T& t) { payload.push_back(t); }
    T& front() { return payload[pos]; }
    void clear() {
        payload.clear();
        pos = 0;
    }
    void pop() { pos++; }
};

}  // namespace internal

}  // namespace atcoder

namespace atcoder {

template <class Cap> struct mf_graph {
  public:
    mf_graph() : _n(0) {}
    explicit mf_graph(int n) : _n(n), g(n) {}

    int add_edge(int from, int to, Cap cap) {
        assert(0 <= from && from < _n);
        assert(0 <= to && to < _n);
        assert(0 <= cap);
        int m = int(pos.size());
        pos.push_back({from, int(g[from].size())});
        int from_id = int(g[from].size());
        int to_id = int(g[to].size());
        if (from == to) to_id++;
        g[from].push_back(_edge{to, to_id, cap});
        g[to].push_back(_edge{from, from_id, 0});
        return m;
    }

    struct edge {
        int from, to;
        Cap cap, flow;
    };

    edge get_edge(int i) {
        int m = int(pos.size());
        assert(0 <= i && i < m);
        auto _e = g[pos[i].first][pos[i].second];
        auto _re = g[_e.to][_e.rev];
        return edge{pos[i].first, _e.to, _e.cap + _re.cap, _re.cap};
    }
    std::vector<edge> edges() {
        int m = int(pos.size());
        std::vector<edge> result;
        for (int i = 0; i < m; i++) {
            result.push_back(get_edge(i));
        }
        return result;
    }
    void change_edge(int i, Cap new_cap, Cap new_flow) {
        int m = int(pos.size());
        assert(0 <= i && i < m);
        assert(0 <= new_flow && new_flow <= new_cap);
        auto& _e = g[pos[i].first][pos[i].second];
        auto& _re = g[_e.to][_e.rev];
        _e.cap = new_cap - new_flow;
        _re.cap = new_flow;
    }

    Cap flow(int s, int t) {
        return flow(s, t, std::numeric_limits<Cap>::max());
    }
    Cap flow(int s, int t, Cap flow_limit) {
        assert(0 <= s && s < _n);
        assert(0 <= t && t < _n);
        assert(s != t);

        std::vector<int> level(_n), iter(_n);
        internal::simple_queue<int> que;

        auto bfs = [&]() {
            std::fill(level.begin(), level.end(), -1);
            level[s] = 0;
            que.clear();
            que.push(s);
            while (!que.empty()) {
                int v = que.front();
                que.pop();
                for (auto e : g[v]) {
                    if (e.cap == 0 || level[e.to] >= 0) continue;
                    level[e.to] = level[v] + 1;
                    if (e.to == t) return;
                    que.push(e.to);
                }
            }
        };
        auto dfs = [&](auto self, int v, Cap up) {
            if (v == s) return up;
            Cap res = 0;
            int level_v = level[v];
            for (int& i = iter[v]; i < int(g[v].size()); i++) {
                _edge& e = g[v][i];
                if (level_v <= level[e.to] || g[e.to][e.rev].cap == 0) continue;
                Cap d =
                    self(self, e.to, std::min(up - res, g[e.to][e.rev].cap));
                if (d <= 0) continue;
                g[v][i].cap += d;
                g[e.to][e.rev].cap -= d;
                res += d;
                if (res == up) return res;
            }
            level[v] = _n;
            return res;
        };

        Cap flow = 0;
        while (flow < flow_limit) {
            bfs();
            if (level[t] == -1) break;
            std::fill(iter.begin(), iter.end(), 0);
            Cap f = dfs(dfs, t, flow_limit - flow);
            if (!f) break;
            flow += f;
        }
        return flow;
    }

    std::vector<bool> min_cut(int s) {
        std::vector<bool> visited(_n);
        internal::simple_queue<int> que;
        que.push(s);
        while (!que.empty()) {
            int p = que.front();
            que.pop();
            visited[p] = true;
            for (auto e : g[p]) {
                if (e.cap && !visited[e.to]) {
                    visited[e.to] = true;
                    que.push(e.to);
                }
            }
        }
        return visited;
    }

  private:
    int _n;
    struct _edge {
        int to, rev;
        Cap cap;
    };
    std::vector<std::pair<int, int>> pos;
    std::vector<std::vector<_edge>> g;
};

}  // namespace atcoder

namespace noya {

/// @brief Gomory-Hu tree representing every pairwise minimum cut of an
/// undirected nonnegative-capacity graph.
template <class Cap> struct gomory_hu_tree_result {
  std::vector<int> parent;
  std::vector<Cap> cut_value;
  std::vector<std::vector<std::pair<int, Cap>>> tree;

  /// @brief Return the minimum cut value between two vertices in O(n) time.
  Cap min_cut(int source, int sink) const {
    const int n = int(tree.size());
    assert(0 <= source && source < n);
    assert(0 <= sink && sink < n);
    if (source == sink) {
      return std::numeric_limits<Cap>::max();
    }
    std::vector<int> stack = {source};
    std::vector<int> previous(n, -1);
    std::vector<Cap> answer(n, std::numeric_limits<Cap>::max());
    previous[source] = source;
    while (!stack.empty()) {
      int vertex = stack.back();
      stack.pop_back();
      if (vertex == sink) {
        return answer[vertex];
      }
      for (auto [next, value] : tree[vertex]) {
        if (previous[next] == -1) {
          previous[next] = vertex;
          answer[next] = std::min(answer[vertex], value);
          stack.push_back(next);
        }
      }
    }
    assert(false);
    return Cap{};
  }
};

/// @brief Build a Gomory-Hu tree in O(n) maximum-flow computations. Each edge
/// is (u, v, capacity); parallel edges are supported and self-loops ignored.
template <class Cap>
gomory_hu_tree_result<Cap>
gomory_hu_tree(int n, const std::vector<std::tuple<int, int, Cap>> &edges) {
  assert(n >= 0);
  gomory_hu_tree_result<Cap> result;
  result.parent.assign(n, 0);
  result.cut_value.assign(n, Cap{});
  result.tree.resize(n);
  if (n <= 1) {
    return result;
  }

  for (const auto &[first, second, capacity] : edges) {
    assert(0 <= first && first < n);
    assert(0 <= second && second < n);
    assert(!(capacity < Cap{}));
  }

  for (int source = 1; source < n; source++) {
    int sink = result.parent[source];
    atcoder::mf_graph<Cap> graph(n);
    for (const auto &[first, second, capacity] : edges) {
      if (first == second || capacity == Cap{}) {
        continue;
      }
      graph.add_edge(first, second, capacity);
      graph.add_edge(second, first, capacity);
    }
    result.cut_value[source] = graph.flow(source, sink);
    std::vector<bool> side = graph.min_cut(source);
    for (int vertex = source + 1; vertex < n; vertex++) {
      if (result.parent[vertex] == sink && side[vertex]) {
        result.parent[vertex] = source;
      }
    }
    if (side[result.parent[sink]]) {
      result.parent[source] = result.parent[sink];
      result.parent[sink] = source;
      std::swap(result.cut_value[source], result.cut_value[sink]);
    }
  }

  for (int vertex = 1; vertex < n; vertex++) {
    int parent = result.parent[vertex];
    Cap value = result.cut_value[vertex];
    result.tree[vertex].emplace_back(parent, value);
    result.tree[parent].emplace_back(vertex, value);
  }
  return result;
}

} // namespace noya