Skip to content

minimum_mean_cycle.hpp

SECTIONGraph INCLUDEnoya/graph/minimum_mean_cycle.hpp

求有向带权图中平均边权最小的环;先拆强连通分量,再做 Karp DP,单环和等权分量直接处理。返回浮点平均值,无环时为空。

Complexity: Time: \(O(V + E + \sum (\mathrm{Vc} \cdot \mathrm{Ec}))\) over nontrivial cyclic SCCs. Space: \(O(V + E + \max (\mathrm{Vc}^{2}))\), including \(O(V)\) recursive SCC depth.

跳到代码 · GitHub ↗

Implementation

当前头文件,省略 include guard;依赖见 #include。

/// @complexity Time: O(V+E+sum(Vc*Ec)) over nontrivial cyclic SCCs.
/// Space: O(V+E+max(Vc^2)), including O(V) recursive SCC depth.

#include "atcoder/internal_scc.hpp"

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

namespace noya {

/// @brief Minimum mean weight of a directed cycle; nullopt for an acyclic graph.
/// Karp's dynamic program runs separately inside each strongly connected
/// component. Weights must convert to finite long double; intermediate sums
/// and differences must remain finite. Precision follows that type.
/// Loops and parallel edges are allowed.
template <class Weight>
std::optional<long double>
minimum_mean_cycle(int n, const std::vector<std::tuple<int, int, Weight>> &es) {
  assert(n >= 0);
  const long double inf = std::numeric_limits<long double>::infinity();
  long double answer = inf;
  struct edge { int from, to; long double cost; };
  std::vector<edge> edges;
  edges.reserve(es.size());
  for (auto [u, v, w] : es) {
    assert(0 <= u && u < n && 0 <= v && v < n);
    long double cost = static_cast<long double>(w);
    assert(std::isfinite(cost));
    if (u == v) answer = std::min(answer, cost);
    else edges.push_back({u, v, cost});
  }
  auto result = [&]() -> std::optional<long double> {
    if (answer == inf) return std::nullopt;
    return answer;
  };
  if (edges.empty()) return result();

  auto [count, id] = [&] {
    atcoder::internal::scc_graph graph(n);
    for (auto e : edges) graph.add_edge(e.from, e.to);
    return graph.scc_ids();
  }();
  std::vector<int> size(count), pos(n);
  for (int v = 0; v < n; ++v) pos[v] = size[id[v]]++;
  std::vector<std::vector<edge>> groups(count);
  if (count == 1) {
    groups[0] = std::move(edges);
  } else {
    for (auto e : edges) if (id[e.from] == id[e.to])
      groups[id[e.from]].push_back({pos[e.from], pos[e.to], e.cost});
    std::vector<edge>().swap(edges);
  }

  for (int c = 0; c < count; ++c) {
    const auto &arcs = groups[c];
    if (arcs.empty()) continue;
    int s = size[c];
    long double low = inf, high = -inf;
    for (auto e : arcs) {
      low = std::min(low, e.cost);
      high = std::max(high, e.cost);
    }
    if (low >= answer) continue;
    // A strongly connected graph with s arcs is one directed cycle.
    if (arcs.size() == std::size_t(s) || low == high) {
      long double mean = low;
      if (low != high) {
        long double sum = 0;
        for (auto e : arcs) sum += e.cost;
        mean = sum / s;
      }
      answer = std::min(answer, mean);
      continue;
    }
    std::vector dis(s + 1, std::vector<long double>(s, inf));
    std::fill(dis[0].begin(), dis[0].end(), 0);
    for (int len = 1; len <= s; ++len)
      for (auto e : arcs)
        dis[len][e.to] = std::min(dis[len][e.to],
                                  dis[len-1][e.from] + e.cost);
    std::vector<long double> maximum(s, -inf);
    // All vertices are reachable at every length from the implicit zero-cost
    // source. Scan complete rows, avoiding a strided read down each column.
    for (int len = 0; len < s; ++len)
      for (int v = 0; v < s; ++v)
        maximum[v] = std::max(maximum[v],
                              (dis[s][v] - dis[len][v]) / (s - len));
    answer = std::min(answer, *std::min_element(maximum.begin(), maximum.end()));
  }
  return result();
}

} // namespace noya
 // NOYA_MINIMUM_MEAN_CYCLE_HPP
#ifndef NOYA_MINIMUM_MEAN_CYCLE_HPP
#define NOYA_MINIMUM_MEAN_CYCLE_HPP 1

/// @complexity Time: O(V+E+sum(Vc*Ec)) over nontrivial cyclic SCCs.
/// Space: O(V+E+max(Vc^2)), including O(V) recursive SCC depth.

#include "atcoder/internal_scc.hpp"

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

namespace noya {

/// @brief Minimum mean weight of a directed cycle; nullopt for an acyclic graph.
/// Karp's dynamic program runs separately inside each strongly connected
/// component. Weights must convert to finite long double; intermediate sums
/// and differences must remain finite. Precision follows that type.
/// Loops and parallel edges are allowed.
template <class Weight>
std::optional<long double>
minimum_mean_cycle(int n, const std::vector<std::tuple<int, int, Weight>> &es) {
  assert(n >= 0);
  const long double inf = std::numeric_limits<long double>::infinity();
  long double answer = inf;
  struct edge { int from, to; long double cost; };
  std::vector<edge> edges;
  edges.reserve(es.size());
  for (auto [u, v, w] : es) {
    assert(0 <= u && u < n && 0 <= v && v < n);
    long double cost = static_cast<long double>(w);
    assert(std::isfinite(cost));
    if (u == v) answer = std::min(answer, cost);
    else edges.push_back({u, v, cost});
  }
  auto result = [&]() -> std::optional<long double> {
    if (answer == inf) return std::nullopt;
    return answer;
  };
  if (edges.empty()) return result();

  auto [count, id] = [&] {
    atcoder::internal::scc_graph graph(n);
    for (auto e : edges) graph.add_edge(e.from, e.to);
    return graph.scc_ids();
  }();
  std::vector<int> size(count), pos(n);
  for (int v = 0; v < n; ++v) pos[v] = size[id[v]]++;
  std::vector<std::vector<edge>> groups(count);
  if (count == 1) {
    groups[0] = std::move(edges);
  } else {
    for (auto e : edges) if (id[e.from] == id[e.to])
      groups[id[e.from]].push_back({pos[e.from], pos[e.to], e.cost});
    std::vector<edge>().swap(edges);
  }

  for (int c = 0; c < count; ++c) {
    const auto &arcs = groups[c];
    if (arcs.empty()) continue;
    int s = size[c];
    long double low = inf, high = -inf;
    for (auto e : arcs) {
      low = std::min(low, e.cost);
      high = std::max(high, e.cost);
    }
    if (low >= answer) continue;
    // A strongly connected graph with s arcs is one directed cycle.
    if (arcs.size() == std::size_t(s) || low == high) {
      long double mean = low;
      if (low != high) {
        long double sum = 0;
        for (auto e : arcs) sum += e.cost;
        mean = sum / s;
      }
      answer = std::min(answer, mean);
      continue;
    }
    std::vector dis(s + 1, std::vector<long double>(s, inf));
    std::fill(dis[0].begin(), dis[0].end(), 0);
    for (int len = 1; len <= s; ++len)
      for (auto e : arcs)
        dis[len][e.to] = std::min(dis[len][e.to],
                                  dis[len-1][e.from] + e.cost);
    std::vector<long double> maximum(s, -inf);
    // All vertices are reachable at every length from the implicit zero-cost
    // source. Scan complete rows, avoiding a strided read down each column.
    for (int len = 0; len < s; ++len)
      for (int v = 0; v < s; ++v)
        maximum[v] = std::max(maximum[v],
                              (dis[s][v] - dis[len][v]) / (s - len));
    answer = std::min(answer, *std::min_element(maximum.begin(), maximum.end()));
  }
  return result();
}

} // namespace noya
#endif // NOYA_MINIMUM_MEAN_CYCLE_HPP
/// @complexity Time: O(V+E+sum(Vc*Ec)) over nontrivial cyclic SCCs.
/// Space: O(V+E+max(Vc^2)), including O(V) recursive SCC depth.

#include <algorithm>
#include <utility>
#include <vector>

#include <algorithm>
#include <utility>
#include <vector>

namespace atcoder {
namespace internal {

template <class E> struct csr {
    std::vector<int> start;
    std::vector<E> elist;
    explicit csr(int n, const std::vector<std::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;
        }
    }
};

}  // namespace internal

}  // namespace atcoder

namespace atcoder {
namespace internal {

// Reference:
// R. Tarjan,
// Depth-First Search and Linear Graph Algorithms
struct scc_graph {
  public:
    explicit scc_graph(int n) : _n(n) {}

    int num_vertices() { return _n; }

    void add_edge(int from, int to) { edges.push_back({from, {to}}); }

    // @return pair of (# of scc, scc id)
    std::pair<int, std::vector<int>> scc_ids() {
        auto g = csr<edge>(_n, edges);
        int now_ord = 0, group_num = 0;
        std::vector<int> visited, low(_n), ord(_n, -1), ids(_n);
        visited.reserve(_n);
        auto dfs = [&](auto self, int v) -> void {
            low[v] = ord[v] = now_ord++;
            visited.push_back(v);
            for (int i = g.start[v]; i < g.start[v + 1]; i++) {
                auto to = g.elist[i].to;
                if (ord[to] == -1) {
                    self(self, to);
                    low[v] = std::min(low[v], low[to]);
                } else {
                    low[v] = std::min(low[v], ord[to]);
                }
            }
            if (low[v] == ord[v]) {
                while (true) {
                    int u = visited.back();
                    visited.pop_back();
                    ord[u] = _n;
                    ids[u] = group_num;
                    if (u == v) break;
                }
                group_num++;
            }
        };
        for (int i = 0; i < _n; i++) {
            if (ord[i] == -1) dfs(dfs, i);
        }
        for (auto& x : ids) {
            x = group_num - 1 - x;
        }
        return {group_num, ids};
    }

    std::vector<std::vector<int>> scc() {
        auto ids = scc_ids();
        int group_num = ids.first;
        std::vector<int> counts(group_num);
        for (auto x : ids.second) counts[x]++;
        std::vector<std::vector<int>> groups(ids.first);
        for (int i = 0; i < group_num; i++) {
            groups[i].reserve(counts[i]);
        }
        for (int i = 0; i < _n; i++) {
            groups[ids.second[i]].push_back(i);
        }
        return groups;
    }

  private:
    int _n;
    struct edge {
        int to;
    };
    std::vector<std::pair<int, edge>> edges;
};

}  // namespace internal

}  // namespace atcoder

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

namespace noya {

/// @brief Minimum mean weight of a directed cycle; nullopt for an acyclic graph.
/// Karp's dynamic program runs separately inside each strongly connected
/// component. Weights must convert to finite long double; intermediate sums
/// and differences must remain finite. Precision follows that type.
/// Loops and parallel edges are allowed.
template <class Weight>
std::optional<long double>
minimum_mean_cycle(int n, const std::vector<std::tuple<int, int, Weight>> &es) {
  assert(n >= 0);
  const long double inf = std::numeric_limits<long double>::infinity();
  long double answer = inf;
  struct edge { int from, to; long double cost; };
  std::vector<edge> edges;
  edges.reserve(es.size());
  for (auto [u, v, w] : es) {
    assert(0 <= u && u < n && 0 <= v && v < n);
    long double cost = static_cast<long double>(w);
    assert(std::isfinite(cost));
    if (u == v) answer = std::min(answer, cost);
    else edges.push_back({u, v, cost});
  }
  auto result = [&]() -> std::optional<long double> {
    if (answer == inf) return std::nullopt;
    return answer;
  };
  if (edges.empty()) return result();

  auto [count, id] = [&] {
    atcoder::internal::scc_graph graph(n);
    for (auto e : edges) graph.add_edge(e.from, e.to);
    return graph.scc_ids();
  }();
  std::vector<int> size(count), pos(n);
  for (int v = 0; v < n; ++v) pos[v] = size[id[v]]++;
  std::vector<std::vector<edge>> groups(count);
  if (count == 1) {
    groups[0] = std::move(edges);
  } else {
    for (auto e : edges) if (id[e.from] == id[e.to])
      groups[id[e.from]].push_back({pos[e.from], pos[e.to], e.cost});
    std::vector<edge>().swap(edges);
  }

  for (int c = 0; c < count; ++c) {
    const auto &arcs = groups[c];
    if (arcs.empty()) continue;
    int s = size[c];
    long double low = inf, high = -inf;
    for (auto e : arcs) {
      low = std::min(low, e.cost);
      high = std::max(high, e.cost);
    }
    if (low >= answer) continue;
    // A strongly connected graph with s arcs is one directed cycle.
    if (arcs.size() == std::size_t(s) || low == high) {
      long double mean = low;
      if (low != high) {
        long double sum = 0;
        for (auto e : arcs) sum += e.cost;
        mean = sum / s;
      }
      answer = std::min(answer, mean);
      continue;
    }
    std::vector dis(s + 1, std::vector<long double>(s, inf));
    std::fill(dis[0].begin(), dis[0].end(), 0);
    for (int len = 1; len <= s; ++len)
      for (auto e : arcs)
        dis[len][e.to] = std::min(dis[len][e.to],
                                  dis[len-1][e.from] + e.cost);
    std::vector<long double> maximum(s, -inf);
    // All vertices are reachable at every length from the implicit zero-cost
    // source. Scan complete rows, avoiding a strided read down each column.
    for (int len = 0; len < s; ++len)
      for (int v = 0; v < s; ++v)
        maximum[v] = std::max(maximum[v],
                              (dis[s][v] - dis[len][v]) / (s - len));
    answer = std::min(answer, *std::min_element(maximum.begin(), maximum.end()));
  }
  return result();
}

} // namespace noya
 // NOYA_MINIMUM_MEAN_CYCLE_HPP