library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub maspypy/library

:warning: flow/longest_shortest_path.hpp

Depends on

Code

#include "flow/mincostflow.hpp"
#include "graph/shortest_path/dijkstra.hpp"

/*
potential p[v]
距離を L 以上にしたい : L<=p[t]-p[s]
辺 (u,v,w)
伸ばす量 max(0,p[v]-p[u]-w)
- t から s に費用-L, 容量INF
- u から v に費用 w, 容量 1
これの循環流
*/

// https://qoj.ac/contest/1435/problem/7737
template <typename T = ll, bool DAG = false>
struct Longest_Shortest_Path {
  int N, s, t;
  T F, L, K;
  bool solved;
  vc<tuple<int, int, T, T>> dat;
  vc<T> pot;
  Longest_Shortest_Path(int N, int s, int t) : N(N), s(s), t(t), F(0), solved(0) {}

  // 現在の長さ, 長さを+1するコスト
  void add(int frm, int to, T length, T cost) {
    assert(0 <= frm && frm < N && 0 <= to && to < N && !solved);
    if (DAG) assert(frm < to);
    dat.eb(frm, to, length, cost);
  }

  T init_dist() {
    Graph<T, 1> G(N);
    for (auto& [a, b, c, d]: dat) G.add(a, b, c);
    G.build();
    auto [dist, par] = dijkstra<T>(G, s);
    return dist[t];
  }

  // 距離が L 以上になるようにせよ. return: min cost.
  T solve_by_target_length(T target_length) {
    L = target_length;
    assert(!solved && L >= init_dist());
    solved = 1;
    Min_Cost_Flow<T, T, DAG> G(N, s, t);
    for (auto& [a, b, length, cost]: dat) { G.add(a, b, cost, length); }
    T ans = -infty<T>;
    for (auto& [x, y]: G.slope()) {
      if (chmax(ans, x * L - y)) F = x;
    }
    return K = ans;
  }

  // コストが K で最大距離にせよ. return: max dist.
  T solve_by_cost(T K) {}

  // frm, to, cost. add_edge 順.
  vc<T> get_potentials() {
    assert(solved);
    if (len(pot)) return pot;
    Min_Cost_Flow<T, T, DAG> G(N, s, t);
    for (auto& [a, b, length, cost]: dat) { G.add(a, b, cost, length); }
    G.flow(F);
    pot = G.get_potentials();
    Graph<T, 1> resG(N);
    auto add = [&](int a, int b, T x) -> void {
      x = x + pot[a] - pot[b];
      resG.add(a, b, x);
    };
    for (auto& e: G.edges()) {
      if (e.cap > e.flow) add(e.frm, e.to, e.cost);
      if (e.flow > 0) add(e.to, e.frm, -e.cost);
    }
    add(s, t, L), add(t, s, -L);
    resG.build();
    vc<T> dist = dijkstra<ll>(resG, s).fi;
    FOR(x, N) pot[x] += dist[x];
    return pot;
  }

  // 変更後の長さ
  vc<T> get_edges() {
    get_potentials();
    vc<T> res;
    for (auto [frm, to, length, cost]: dat) { res.eb(max<T>(length, pot[to] - pot[frm])); }
    return res;
  }
};
#line 2 "flow/mincostflow.hpp"

// atcoder library のものを改変
namespace internal {
template <class E>
struct csr {
  vector<int> start;
  vector<E> elist;
  explicit csr(int n, const vector<pair<int, E>>& edges) : start(n + 1), elist(edges.size()) {
    for (auto e: edges) { start[e.first + 1]++; }
    for (int i = 1; i <= n; i++) { start[i] += start[i - 1]; }
    auto counter = start;
    for (auto e: edges) { elist[counter[e.first]++] = e.second; }
  }
};

template <class T>
struct simple_queue {
  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

/*
・atcoder library をすこし改変したもの
・DAG = true であれば、負辺 OK (1 回目の最短路を dp で行う)
ただし、頂点番号は toposort されていることを仮定している。
*/
template <class Cap = int, class Cost = ll, bool DAG = false>
struct Min_Cost_Flow {
public:
  Min_Cost_Flow() {}
  explicit Min_Cost_Flow(int n, int source, int sink) : n(n), source(source), sink(sink) {
    assert(0 <= source && source < n);
    assert(0 <= sink && sink < n);
    assert(source != sink);
  }

  // frm, to, cap, cost
  int add(int frm, int to, Cap cap, Cost cost) {
    assert(0 <= frm && frm < n);
    assert(0 <= to && to < n);
    assert(0 <= cap);
    assert(DAG || 0 <= cost);
    if (DAG) assert(frm < to);
    int m = int(_edges.size());
    _edges.push_back({frm, to, cap, 0, cost});
    return m;
  }

  void debug() {
    print("flow graph");
    print("frm, to, cap, cost");
    for (auto&& [frm, to, cap, flow, cost]: _edges) { print(frm, to, cap, cost); }
  }

  struct edge {
    int frm, to;
    Cap cap, flow;
    Cost cost;
  };

  edge get_edge(int i) {
    int m = int(_edges.size());
    assert(0 <= i && i < m);
    return _edges[i];
  }
  vector<edge> edges() { return _edges; }

  // (流量, 費用)
  pair<Cap, Cost> flow() { return flow(infty<Cap>); }
  // (流量, 費用)
  pair<Cap, Cost> flow(Cap flow_limit) { return slope(flow_limit).back(); }
  vector<pair<Cap, Cost>> slope() { return slope(infty<Cap>); }
  vector<pair<Cap, Cost>> slope(Cap flow_limit) {
    int m = int(_edges.size());
    vector<int> edge_idx(m);

    auto g = [&]() {
      vector<int> degree(n), redge_idx(m);
      vector<pair<int, _edge>> elist;
      elist.reserve(2 * m);
      for (int i = 0; i < m; i++) {
        auto e = _edges[i];
        edge_idx[i] = degree[e.frm]++;
        redge_idx[i] = degree[e.to]++;
        elist.push_back({e.frm, {e.to, -1, e.cap - e.flow, e.cost}});
        elist.push_back({e.to, {e.frm, -1, e.flow, -e.cost}});
      }
      auto _g = internal::csr<_edge>(n, elist);
      for (int i = 0; i < m; i++) {
        auto e = _edges[i];
        edge_idx[i] += _g.start[e.frm];
        redge_idx[i] += _g.start[e.to];
        _g.elist[edge_idx[i]].rev = redge_idx[i];
        _g.elist[redge_idx[i]].rev = edge_idx[i];
      }
      return _g;
    }();

    auto result = slope(g, flow_limit);

    for (int i = 0; i < m; i++) {
      auto e = g.elist[edge_idx[i]];
      _edges[i].flow = _edges[i].cap - e.cap;
    }

    return result;
  }

  // O(F(N+M)) くらい使って経路復元
  vvc<int> path_decomposition() {
    vvc<int> TO(n);
    for (auto&& e: edges()) { FOR(e.flow) TO[e.frm].eb(e.to); }
    vvc<int> res;
    vc<int> vis(n);

    while (!TO[source].empty()) {
      vc<int> path = {source};
      vis[source] = 1;
      while (path.back() != sink) {
        int to = POP(TO[path.back()]);
        while (vis[to]) { vis[POP(path)] = 0; }
        path.eb(to), vis[to] = 1;
      }
      for (auto&& v: path) vis[v] = 0;
      res.eb(path);
    }
    return res;
  }

  vc<Cost> get_potentials() { return potential; }

private:
  int n, source, sink;
  vector<edge> _edges;

  // inside edge
  struct _edge {
    int to, rev;
    Cap cap;
    Cost cost;
  };

  vc<Cost> potential;

  vector<pair<Cap, Cost>> slope(internal::csr<_edge>& g, Cap flow_limit) {
    if (DAG) assert(source == 0 && sink == n - 1);
    vector<pair<Cost, Cost>> dual_dist(n);
    vector<int> prev_e(n);
    vector<bool> vis(n);
    struct Q {
      Cost key;
      int to;
      bool operator<(Q r) const { return key > r.key; }
    };
    vector<int> que_min;
    vector<Q> que;
    auto dual_ref = [&]() {
      for (int i = 0; i < n; i++) { dual_dist[i].second = infty<Cost>; }
      fill(vis.begin(), vis.end(), false);
      que_min.clear();
      que.clear();

      // que[0..heap_r) was heapified
      size_t heap_r = 0;

      dual_dist[source].second = 0;
      que_min.push_back(source);
      while (!que_min.empty() || !que.empty()) {
        int v;
        if (!que_min.empty()) {
          v = que_min.back();
          que_min.pop_back();
        } else {
          while (heap_r < que.size()) {
            heap_r++;
            push_heap(que.begin(), que.begin() + heap_r);
          }
          v = que.front().to;
          pop_heap(que.begin(), que.end());
          que.pop_back();
          heap_r--;
        }
        if (vis[v]) continue;
        vis[v] = true;
        if (v == sink) break;
        Cost dual_v = dual_dist[v].first, dist_v = dual_dist[v].second;
        for (int i = g.start[v]; i < g.start[v + 1]; i++) {
          auto e = g.elist[i];
          if (!e.cap) continue;
          Cost cost = e.cost - dual_dist[e.to].first + dual_v;
          if (dual_dist[e.to].second > dist_v + cost) {
            Cost dist_to = dist_v + cost;
            dual_dist[e.to].second = dist_to;
            prev_e[e.to] = e.rev;
            if (dist_to == dist_v) {
              que_min.push_back(e.to);
            } else {
              que.push_back(Q{dist_to, e.to});
            }
          }
        }
      }
      if (!vis[sink]) { return false; }

      for (int v = 0; v < n; v++) {
        if (!vis[v]) continue;
        dual_dist[v].first -= dual_dist[sink].second - dual_dist[v].second;
      }
      return true;
    };

    auto dual_ref_dag = [&]() {
      FOR(i, n) dual_dist[i].se = infty<Cost>;
      dual_dist[source].se = 0;
      fill(vis.begin(), vis.end(), false);
      vis[0] = true;

      FOR(v, n) {
        if (!vis[v]) continue;
        Cost dual_v = dual_dist[v].fi, dist_v = dual_dist[v].se;
        for (int i = g.start[v]; i < g.start[v + 1]; i++) {
          auto e = g.elist[i];
          if (!e.cap) continue;
          Cost cost = e.cost - dual_dist[e.to].fi + dual_v;
          if (dual_dist[e.to].se > dist_v + cost) {
            vis[e.to] = true;
            Cost dist_to = dist_v + cost;
            dual_dist[e.to].second = dist_to;
            prev_e[e.to] = e.rev;
          }
        }
      }
      if (!vis[sink]) { return false; }

      for (int v = 0; v < n; v++) {
        if (!vis[v]) continue;
        dual_dist[v].fi -= dual_dist[sink].se - dual_dist[v].se;
      }
      return true;
    };

    Cap flow = 0;
    Cost cost = 0, prev_cost_per_flow = -1;
    vector<pair<Cap, Cost>> result = {{Cap(0), Cost(0)}};
    while (flow < flow_limit) {
      if (DAG && flow == 0) {
        if (!dual_ref_dag()) break;
      } else {
        if (!dual_ref()) break;
      }
      Cap c = flow_limit - flow;
      for (int v = sink; v != source; v = g.elist[prev_e[v]].to) { c = min(c, g.elist[g.elist[prev_e[v]].rev].cap); }
      for (int v = sink; v != source; v = g.elist[prev_e[v]].to) {
        auto& e = g.elist[prev_e[v]];
        e.cap += c;
        g.elist[e.rev].cap -= c;
      }
      Cost d = -dual_dist[source].first;
      flow += c;
      cost += c * d;
      if (prev_cost_per_flow == d) { result.pop_back(); }
      result.push_back({flow, cost});
      prev_cost_per_flow = d;
    }
    dual_ref();
    potential.resize(n);
    FOR(v, n) potential[v] = dual_dist[v].fi;
    return result;
  }
};
#line 2 "graph/base.hpp"

template <typename T>
struct Edge {
  int frm, to;
  T cost;
  int id;
};

template <typename T = int, bool directed = false>
struct Graph {
  static constexpr bool is_directed = directed;
  int N, M;
  using cost_type = T;
  using edge_type = Edge<T>;
  vector<edge_type> edges;
  vector<int> indptr;
  vector<edge_type> csr_edges;
  vc<int> vc_deg, vc_indeg, vc_outdeg;
  bool prepared;

  class OutgoingEdges {
  public:
    OutgoingEdges(const Graph* G, int l, int r) : G(G), l(l), r(r) {}

    const edge_type* begin() const {
      if (l == r) { return 0; }
      return &G->csr_edges[l];
    }

    const edge_type* end() const {
      if (l == r) { return 0; }
      return &G->csr_edges[r];
    }

  private:
    const Graph* G;
    int l, r;
  };

  bool is_prepared() { return prepared; }

  Graph() : N(0), M(0), prepared(0) {}
  Graph(int N) : N(N), M(0), prepared(0) {}

  void build(int n) {
    N = n, M = 0;
    prepared = 0;
    edges.clear();
    indptr.clear();
    csr_edges.clear();
    vc_deg.clear();
    vc_indeg.clear();
    vc_outdeg.clear();
  }

  void add(int frm, int to, T cost = 1, int i = -1) {
    assert(!prepared);
    assert(0 <= frm && 0 <= to && to < N);
    if (i == -1) i = M;
    auto e = edge_type({frm, to, cost, i});
    edges.eb(e);
    ++M;
  }

#ifdef FASTIO
  // wt, off
  void read_tree(bool wt = false, int off = 1) { read_graph(N - 1, wt, off); }

  void read_graph(int M, bool wt = false, int off = 1) {
    for (int m = 0; m < M; ++m) {
      INT(a, b);
      a -= off, b -= off;
      if (!wt) {
        add(a, b);
      } else {
        T c;
        read(c);
        add(a, b, c);
      }
    }
    build();
  }
#endif

  void build() {
    assert(!prepared);
    prepared = true;
    indptr.assign(N + 1, 0);
    for (auto&& e: edges) {
      indptr[e.frm + 1]++;
      if (!directed) indptr[e.to + 1]++;
    }
    for (int v = 0; v < N; ++v) { indptr[v + 1] += indptr[v]; }
    auto counter = indptr;
    csr_edges.resize(indptr.back() + 1);
    for (auto&& e: edges) {
      csr_edges[counter[e.frm]++] = e;
      if (!directed)
        csr_edges[counter[e.to]++] = edge_type({e.to, e.frm, e.cost, e.id});
    }
  }

  OutgoingEdges operator[](int v) const {
    assert(prepared);
    return {this, indptr[v], indptr[v + 1]};
  }

  vc<int> deg_array() {
    if (vc_deg.empty()) calc_deg();
    return vc_deg;
  }

  pair<vc<int>, vc<int>> deg_array_inout() {
    if (vc_indeg.empty()) calc_deg_inout();
    return {vc_indeg, vc_outdeg};
  }

  int deg(int v) {
    if (vc_deg.empty()) calc_deg();
    return vc_deg[v];
  }

  int in_deg(int v) {
    if (vc_indeg.empty()) calc_deg_inout();
    return vc_indeg[v];
  }

  int out_deg(int v) {
    if (vc_outdeg.empty()) calc_deg_inout();
    return vc_outdeg[v];
  }

#ifdef FASTIO
  void debug() {
    print("Graph");
    if (!prepared) {
      print("frm to cost id");
      for (auto&& e: edges) print(e.frm, e.to, e.cost, e.id);
    } else {
      print("indptr", indptr);
      print("frm to cost id");
      FOR(v, N) for (auto&& e: (*this)[v]) print(e.frm, e.to, e.cost, e.id);
    }
  }
#endif

  vc<int> new_idx;
  vc<bool> used_e;

  // G における頂点 V[i] が、新しいグラフで i になるようにする
  // {G, es}
  // sum(deg(v)) の計算量になっていて、
  // 新しいグラフの n+m より大きい可能性があるので注意
  Graph<T, directed> rearrange(vc<int> V, bool keep_eid = 0) {
    if (len(new_idx) != N) new_idx.assign(N, -1);
    int n = len(V);
    FOR(i, n) new_idx[V[i]] = i;
    Graph<T, directed> G(n);
    vc<int> history;
    FOR(i, n) {
      for (auto&& e: (*this)[V[i]]) {
        if (len(used_e) <= e.id) used_e.resize(e.id + 1);
        if (used_e[e.id]) continue;
        int a = e.frm, b = e.to;
        if (new_idx[a] != -1 && new_idx[b] != -1) {
          history.eb(e.id);
          used_e[e.id] = 1;
          int eid = (keep_eid ? e.id : -1);
          G.add(new_idx[a], new_idx[b], e.cost, eid);
        }
      }
    }
    FOR(i, n) new_idx[V[i]] = -1;
    for (auto&& eid: history) used_e[eid] = 0;
    G.build();
    return G;
  }

  Graph<T, true> to_directed_tree(int root = -1) {
    if (root == -1) root = 0;
    assert(!is_directed && prepared && M == N - 1);
    Graph<T, true> G1(N);
    vc<int> par(N, -1);
    auto dfs = [&](auto& dfs, int v) -> void {
      for (auto& e: (*this)[v]) {
        if (e.to == par[v]) continue;
        par[e.to] = v, dfs(dfs, e.to);
      }
    };
    dfs(dfs, root);
    for (auto& e: edges) {
      int a = e.frm, b = e.to;
      if (par[a] == b) swap(a, b);
      assert(par[b] == a);
      G1.add(a, b, e.cost);
    }
    G1.build();
    return G1;
  }

private:
  void calc_deg() {
    assert(vc_deg.empty());
    vc_deg.resize(N);
    for (auto&& e: edges) vc_deg[e.frm]++, vc_deg[e.to]++;
  }

  void calc_deg_inout() {
    assert(vc_indeg.empty());
    vc_indeg.resize(N);
    vc_outdeg.resize(N);
    for (auto&& e: edges) { vc_indeg[e.to]++, vc_outdeg[e.frm]++; }
  }
};
#line 3 "graph/shortest_path/dijkstra.hpp"

template <typename T, typename GT>
pair<vc<T>, vc<int>> dijkstra_dense(GT& G, int s) {
  const int N = G.N;
  vc<T> dist(N, infty<T>);
  vc<int> par(N, -1);
  vc<bool> done(N);
  dist[s] = 0;
  while (1) {
    int v = -1;
    T mi = infty<T>;
    FOR(i, N) {
      if (!done[i] && chmin(mi, dist[i])) v = i;
    }
    if (v == -1) break;
    done[v] = 1;
    for (auto&& e: G[v]) {
      if (chmin(dist[e.to], dist[v] + e.cost)) par[e.to] = v;
    }
  }
  return {dist, par};
}

template <typename T, typename GT, bool DENSE = false>
pair<vc<T>, vc<int>> dijkstra(GT& G, int v) {
  if (DENSE) return dijkstra_dense<T>(G, v);
  auto N = G.N;
  vector<T> dist(N, infty<T>);
  vector<int> par(N, -1);
  using P = pair<T, int>;

  priority_queue<P, vector<P>, greater<P>> que;

  dist[v] = 0;
  que.emplace(0, v);
  while (!que.empty()) {
    auto [dv, v] = que.top();
    que.pop();
    if (dv > dist[v]) continue;
    for (auto&& e: G[v]) {
      if (chmin(dist[e.to], dist[e.frm] + e.cost)) {
        par[e.to] = e.frm;
        que.emplace(dist[e.to], e.to);
      }
    }
  }
  return {dist, par};
}

// 多点スタート。[dist, par, root]
template <typename T, typename GT>
tuple<vc<T>, vc<int>, vc<int>> dijkstra(GT& G, vc<int> vs) {
  assert(G.is_prepared());
  int N = G.N;
  vc<T> dist(N, infty<T>);
  vc<int> par(N, -1);
  vc<int> root(N, -1);

  using P = pair<T, int>;

  priority_queue<P, vector<P>, greater<P>> que;

  for (auto&& v: vs) {
    dist[v] = 0;
    root[v] = v;
    que.emplace(T(0), v);
  }

  while (!que.empty()) {
    auto [dv, v] = que.top();
    que.pop();
    if (dv > dist[v]) continue;
    for (auto&& e: G[v]) {
      if (chmin(dist[e.to], dist[e.frm] + e.cost)) {
        root[e.to] = root[e.frm];
        par[e.to] = e.frm;
        que.push(mp(dist[e.to], e.to));
      }
    }
  }
  return {dist, par, root};
}
#line 3 "flow/longest_shortest_path.hpp"

/*
potential p[v]
距離を L 以上にしたい : L<=p[t]-p[s]
辺 (u,v,w)
伸ばす量 max(0,p[v]-p[u]-w)
- t から s に費用-L, 容量INF
- u から v に費用 w, 容量 1
これの循環流
*/

// https://qoj.ac/contest/1435/problem/7737
template <typename T = ll, bool DAG = false>
struct Longest_Shortest_Path {
  int N, s, t;
  T F, L, K;
  bool solved;
  vc<tuple<int, int, T, T>> dat;
  vc<T> pot;
  Longest_Shortest_Path(int N, int s, int t) : N(N), s(s), t(t), F(0), solved(0) {}

  // 現在の長さ, 長さを+1するコスト
  void add(int frm, int to, T length, T cost) {
    assert(0 <= frm && frm < N && 0 <= to && to < N && !solved);
    if (DAG) assert(frm < to);
    dat.eb(frm, to, length, cost);
  }

  T init_dist() {
    Graph<T, 1> G(N);
    for (auto& [a, b, c, d]: dat) G.add(a, b, c);
    G.build();
    auto [dist, par] = dijkstra<T>(G, s);
    return dist[t];
  }

  // 距離が L 以上になるようにせよ. return: min cost.
  T solve_by_target_length(T target_length) {
    L = target_length;
    assert(!solved && L >= init_dist());
    solved = 1;
    Min_Cost_Flow<T, T, DAG> G(N, s, t);
    for (auto& [a, b, length, cost]: dat) { G.add(a, b, cost, length); }
    T ans = -infty<T>;
    for (auto& [x, y]: G.slope()) {
      if (chmax(ans, x * L - y)) F = x;
    }
    return K = ans;
  }

  // コストが K で最大距離にせよ. return: max dist.
  T solve_by_cost(T K) {}

  // frm, to, cost. add_edge 順.
  vc<T> get_potentials() {
    assert(solved);
    if (len(pot)) return pot;
    Min_Cost_Flow<T, T, DAG> G(N, s, t);
    for (auto& [a, b, length, cost]: dat) { G.add(a, b, cost, length); }
    G.flow(F);
    pot = G.get_potentials();
    Graph<T, 1> resG(N);
    auto add = [&](int a, int b, T x) -> void {
      x = x + pot[a] - pot[b];
      resG.add(a, b, x);
    };
    for (auto& e: G.edges()) {
      if (e.cap > e.flow) add(e.frm, e.to, e.cost);
      if (e.flow > 0) add(e.to, e.frm, -e.cost);
    }
    add(s, t, L), add(t, s, -L);
    resG.build();
    vc<T> dist = dijkstra<ll>(resG, s).fi;
    FOR(x, N) pot[x] += dist[x];
    return pot;
  }

  // 変更後の長さ
  vc<T> get_edges() {
    get_potentials();
    vc<T> res;
    for (auto [frm, to, length, cost]: dat) { res.eb(max<T>(length, pot[to] - pot[frm])); }
    return res;
  }
};
Back to top page