cpp-library

This documentation is automatically generated by competitive-verifier/competitive-verifier

View the Project on GitHub shino16/cpp-library

:warning: graph/all_pairs_distances.hpp

Depends on

Code

#pragma once
#include "graph/bellman_ford.hpp"
#include "graph/dijkstra.hpp"

template <class G>
class reduced_graph : public graph_trait<G> {
 public:
  reduced_graph(G& graph, vector<weight_t<G>>& potential)
      : graph_trait<G>(graph), potential(potential) {}
  template <class F>
  void adj(int v, F&& f) const {
    graph_trait<G>::adj(v, [&](auto&& e) {
      weight_t<G> reduced_cost = e.w() + potential[v] - potential[e.to];
      f(weighted_edge<weight_t<G>>{e.to, reduced_cost});
    });
  }

 private:
  vector<weight_t<G>>& potential;
};

// graph should be strongly connected
template <class G>
optional<vector<vector<weight_t<G>>>> all_pairs_distances(G& graph) {
  const weight_t<G> inf = numeric_limits<weight_t<G>>::max();
  graph_trait<G> g(graph);
  vector<vector<weight_t<G>>> dist(g.size());
  auto [fail, potential] = bellman_ford(graph, 0);
  bool reachable = count(all(potential), inf) == 0;
  if (fail || !reachable) return nullopt;

  reduced_graph<G> g2(graph, potential);

  dist[0] = potential;
  rep2(v, 1, g.size()) {
    dist[v] = dijkstra(g2, v);
    rep(u, g.size()) dist[v][u] =
        dist[v][u] == inf ? inf : dist[v][u] - potential[v] + potential[u];
  }
  return optional(move(dist));
}
#line 2 "prelude.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using vc = vector<char>;
#define rep2(i, m, n) for (auto i = (m); i < (n); i++)
#define rep(i, n) rep2(i, 0, n)
#define repr2(i, m, n) for (auto i = (n); i-- > (m);)
#define repr(i, n) repr2(i, 0, n)
#define all(x) begin(x), end(x)
auto ndvec(int n, auto e) { return vector(n, e); }
auto ndvec(int n, auto ...e) { return vector(n, ndvec(e...)); }
auto comp_key(auto&& f) { return [&](auto&& a, auto&& b) { return f(a) < f(b); }; }
auto& max(const auto& a, const auto& b) { return a < b ? b : a; }
auto& min(const auto& a, const auto& b) { return b < a ? b : a; }
#if __cpp_lib_ranges
namespace R = std::ranges;
namespace V = std::views;
#endif
#line 3 "graph/traits.hpp"

struct unit_edge {
  int to;
  operator int() const { return to; }
  int w() const { return 1; }
};

template <class Weight>
struct weighted_edge {
  int to;
  Weight weight;
  operator int() const { return to; }
  Weight w() const { return weight; }
};

template <class Inner>
struct basic_graph {
  using weight_type = void;
  const Inner& inner;
  basic_graph(const Inner& g) : inner(g) { }
  template <class F>
  void adj(int v, F f) const {
    for (auto u : inner[v]) f(unit_edge{u});
  }
  int deg(int v) const { return inner[v].size(); }
};

template <class Inner, class Weight>
struct basic_weighted_graph {
  using weight_type = Weight;
  const Inner& inner;
  basic_weighted_graph(const Inner& g) : inner(g) { }
  template <class F>
  void adj(int v, F f) const {
    for (auto [u, w] : inner[v]) f(weighted_edge<weight_type>{u, w});
  }
  int deg(int v) const { return inner[v].size(); }
};

template <class Inner>
struct graph_trait {
  using weight_type = typename Inner::weight_type;
  const Inner& g;
  graph_trait(const Inner& g) : g(g) { }
  int size() const { return g.size(); }
  template <class F>
  void adj(int v, F f) const {
    g.adj(v, f);
  }
  decltype(auto) operator[](int v) const { return g[v]; }
};

template <class T>
constexpr bool is_weighted_v =
    !is_same_v<typename graph_trait<T>::weight_type, void>;

template <class T>
using weight_t =
    conditional_t<is_weighted_v<T>, typename graph_trait<T>::weight_type, int>;

template <class T>
using edge_t =
    conditional_t<is_weighted_v<T>, weighted_edge<weight_t<T>>, unit_edge>;

template <size_t N>
struct graph_trait<vector<int>[N]> : basic_graph<vector<int>[N]> {
  using basic_graph<vector<int>[N]>::basic_graph;
  int size() const { return N; }
};

template <>
struct graph_trait<vector<vector<int>>> : basic_graph<vector<vector<int>>> {
  using basic_graph<vector<vector<int>>>::basic_graph;
  int size() const { return this->inner.size(); }
};

template <size_t N, class Weight>
struct graph_trait<vector<pair<int, Weight>>[N]>
    : basic_weighted_graph<vector<pair<int, Weight>>[N], Weight> {
      using basic_weighted_graph<
          vector<pair<int, Weight>>[N], Weight>::basic_weighted_graph;
      int size() const { return N; }
    };

template <class Weight>
struct graph_trait<vector<vector<pair<int, Weight>>>>
    : basic_weighted_graph<vector<vector<pair<int, Weight>>>, Weight> {
  using basic_weighted_graph<
      vector<vector<pair<int, Weight>>>, Weight>::basic_weighted_graph;
  int size() const { return this->inner.size(); }
};
#line 3 "range.hpp"

template <class It>
struct range : pair<It, It> {
  using pair<It, It>::pair;
  It begin() const { return this->first; }
  It end() const { return this->second; }
  It cbegin() const { return begin(); }
  It cend() const { return end(); }
  int size() const { return this->second - this->first; }
};
#line 4 "graph/csr.hpp"

template <size_t>
struct stdin_reader;

template <class Weight = void>
class csr_graph {
 private:
  struct directed_t {};

 public:
  using weight_type = Weight;

  csr_graph() = default;
  template <class It>
  csr_graph(int n, It e, It e_last) : n(n), m(distance(e, e_last)) {
    init<false>(e, e_last);
  }
  template <size_t Size = 1 << 26>
  csr_graph(int n, int m, stdin_reader<Size>& read) : n(n), m(m) {
    auto e = read_e(read);
    init<false>(all(e));
  }

  template <class It>
  static csr_graph directed(int n, It e, It e_last) {
    return csr_graph(directed_t{}, n, e, e_last);
  }
  template <size_t Size = 1 << 26>
  static csr_graph directed(int n, int m, stdin_reader<Size>& read) {
    return csr_graph(directed_t{}, n, m, read);
  }

  template <size_t Size = 1 << 26>
  static csr_graph tree(int n, stdin_reader<Size>& read) {
    return csr_graph(n, n - 1, read);
  }
  template <size_t Size = 1 << 26>
  static csr_graph tree(stdin_reader<Size>& read) {
    int n = read;
    return csr_graph(n, n - 1, read);
  }

  int size() const { return n; }
  range<typename vector<edge_t<csr_graph>>::iterator> operator[](int v) const {
    return {ls[v], rs[v]};
  }
  int deg(int v) { return rs[v] - ls[v]; }
  template <class F>
  void adj(int v, F f) const {
    for_each(ls[v], rs[v], f);
  }

 private:
  template <class It>
  csr_graph(directed_t, int n, It e, It e_last) : n(n), m(distance(e, e_last)) {
    init<true>(e, e_last);
  }
  template <size_t Size = 1 << 26>
  csr_graph(directed_t, int n, int m, stdin_reader<Size>& read) : n(n), m(m) {
    auto e = read_e(read);
    init<true>(all(e));
  }

  vector<typename vector<edge_t<csr_graph>>::iterator> ls, rs;
  int n, m;
  vector<edge_t<csr_graph>> es;
  template <bool OneBased = true, size_t Size = 1 << 26>
  auto read_e(stdin_reader<Size>& read) {
    using E = conditional_t<is_weighted_v<csr_graph>, tuple<int, int, Weight>,
                            pair<int, int>>;
    vector<E> res(m);
    for (auto& e : res) {
      read(e);
      if (OneBased) get<0>(e)--, get<1>(e)--;
    }
    return res;
  }
  template <bool Directed, class It>
  void init(It e, It e_last) {
    if (!Directed) m *= 2;
    es.resize(m);
    ls.resize(n), rs.resize(n);
    vector<int> sz(n);
    for (auto it = e; it != e_last; it++) {
      int from = get<0>(*it), to = get<1>(*it);
      sz[from]++;
      if (!Directed) sz[to]++;
    }
    partial_sum(all(sz), sz.begin());
    rep(v, n) ls[v] = rs[v] = es.begin() + sz[v];
    for (auto it = e; it != e_last; it++) {
      int from = get<0>(*it), to = get<1>(*it);
      if constexpr (is_weighted_v<csr_graph>)
        *--ls[from] = edge_t<csr_graph>{to, get<2>(*it)};
      else
        *--ls[from] = edge_t<csr_graph>{to};
      if (!Directed) {
        if constexpr (is_weighted_v<csr_graph>)
          *--ls[to] = edge_t<csr_graph>{from, get<2>(*it)};
        else
          *--ls[to] = edge_t<csr_graph>{from};
      }
    }
  }
};
#line 3 "graph/bellman_ford.hpp"

// (fail, dist)
template <class G>
pair<bool, vector<weight_t<G>>> bellman_ford(G& graph, int s) {
  const weight_t<G> inf = numeric_limits<weight_t<G>>::max();
  graph_trait<G> g(graph);
  vector<weight_t<G>> dist(g.size(), inf);
  dist[s] = 0;
  bool success = false;
  rep(t, g.size()) {
    bool updated = false;
    rep(v, g.size()) if (dist[v] != inf) g.adj(v, [&](auto&& e) {
      if (dist[e.to] > dist[v] + e.w())
        updated = true,
        dist[e.to] = dist[v] + e.w();
    });
    if (!updated) {
      success = true;
      break;
    }
  }
  for (auto& d : dist) if (d >= inf / 2) d = numeric_limits<weight_t<G>>::max();
  return {!success, move(dist)};
}
#line 2 "ds/heap.hpp"

template <class T, class Cmp = less<>>
class heap {
 public:
  heap(Cmp cmp = Cmp()) : cmp(cmp), data(1) {}
  heap(int n, Cmp cmp = Cmp()) : cmp(cmp), data(1), pos(n, -1) {}
  // moves out from [first, last)
  template <class It>
  heap(It first, It last, Cmp cmp = Cmp()) : cmp(cmp) {
    init(first, last);
  }
  bool empty() const { return data.size() == 1; }
  int size() const { return data.size() - 1; }
  void reserve(int n) { pos.resize(max<size_t>(pos.size(), n), -1); }
  bool contains(int i) const { return i < pos.size() && pos[i] != -1; }
  void insert(int i, T x) {
    reserve(i + 1);
    pos[i] = data.size(), data.emplace_back(x, i);
    pushup(pos[i]);
  }
  void modify(int i, T x) {
    int v = pos[i];
    bool decrease = cmp(x, exchange(data[v].first, x));
    return decrease ? merge(v) : pushup(v);
  }
  void insert_or_modify(int i, T x) {
    return contains(i) ? modify(i, x) : insert(i, x);
  }
  const pair<T, int>& top() const { return data[1]; }
  pair<T, int> pop() { return erase(data[1].second); }
  pair<T, int> erase(int i) {
    int idx = exchange(pos[i], -1);
    pair<T, int> res = exchange(data[idx], move(data.back()));
    data.pop_back();
    if (idx != data.size()) pos[data[idx].second] = idx, merge(idx);
    return res;
  }

 private:
  Cmp cmp;
  vector<pair<T, int>> data;
  vector<int> pos;
  // moves out from [first, last)
  template <class It>
  void init(It first, It last) {
    data.resize(1), pos.clear();
    int n = distance(first, last);
    data.reserve(n), pos.resize(n);
    for (auto it = first; it != last; it++)
      data.emplace_back(data.size(), move(*it));
    iota(all(pos), 1);
    repr2(v, 1, n / 2 + 1) merge(v);
  }
  void merge(int v) {
    if (v * 2 >= data.size()) return;
    int l = v * 2, r = v * 2 + 1;
    int c = r < data.size() && cmp(data[l].first, data[r].first) ? r : l;
    if (cmp(data[v].first, data[c].first)) {
      swap(data[v], data[c]), swap(pos[data[v].second], pos[data[c].second]);
      merge(c);
    }
  }
  void pushup(int v) {
    for (int p = v / 2; p && cmp(data[p].first, data[v].first); v /= 2, p /= 2)
      swap(data[p], data[v]), swap(pos[data[p].second], pos[data[v].second]);
  }
};
#line 4 "graph/dijkstra.hpp"

template <class G, class Iter>
vector<weight_t<G>> dijkstra(
    const G& graph, Iter s_it, Iter s_last,
    weight_t<G> M = numeric_limits<weight_t<G>>::max()) {
  graph_trait<G> g(graph);
  vector<weight_t<G>> dist(g.size(), M);
  heap<weight_t<G>, greater<>> hp;
  while (s_it != s_last)
    hp.insert(*s_it, weight_t<G>(0)), dist[*s_it++] = weight_t<G>(0);
  while (!hp.empty()) {
    auto [w, v] = hp.pop();
    g.adj(v, [&, v = v](auto&& e) {
      if (dist[e.to] > dist[v] + e.w())
        hp.insert_or_modify(e.to, dist[e.to] = dist[v] + e.w());
    });
  }
  return dist;
}

template <class G>
vector<weight_t<G>> dijkstra(
    const G& graph, int s, weight_t<G> M = numeric_limits<weight_t<G>>::max()) {
  return dijkstra(graph, &s, &s + 1, M);
}
#line 4 "graph/all_pairs_distances.hpp"

template <class G>
class reduced_graph : public graph_trait<G> {
 public:
  reduced_graph(G& graph, vector<weight_t<G>>& potential)
      : graph_trait<G>(graph), potential(potential) {}
  template <class F>
  void adj(int v, F&& f) const {
    graph_trait<G>::adj(v, [&](auto&& e) {
      weight_t<G> reduced_cost = e.w() + potential[v] - potential[e.to];
      f(weighted_edge<weight_t<G>>{e.to, reduced_cost});
    });
  }

 private:
  vector<weight_t<G>>& potential;
};

// graph should be strongly connected
template <class G>
optional<vector<vector<weight_t<G>>>> all_pairs_distances(G& graph) {
  const weight_t<G> inf = numeric_limits<weight_t<G>>::max();
  graph_trait<G> g(graph);
  vector<vector<weight_t<G>>> dist(g.size());
  auto [fail, potential] = bellman_ford(graph, 0);
  bool reachable = count(all(potential), inf) == 0;
  if (fail || !reachable) return nullopt;

  reduced_graph<G> g2(graph, potential);

  dist[0] = potential;
  rep2(v, 1, g.size()) {
    dist[v] = dijkstra(g2, v);
    rep(u, g.size()) dist[v][u] =
        dist[v][u] == inf ? inf : dist[v][u] - potential[v] + potential[u];
  }
  return optional(move(dist));
}
Back to top page