競技プログラミング用の C++ ライブラリ
#include "src/graph/graph_util.hpp"グラフ Graph<Cost> を受け取る関数です。
| 関数 | 対象 | 説明 | 計算量 |
|---|---|---|---|
is_bipartite(g) |
無向 | 二部グラフか | $O(n + m)$ |
bipartite_coloring(g) |
無向 | 二部グラフなら各頂点を 0, 1 に彩色した結果 (各連結成分で番号最小の頂点を 0 にする)。二部グラフでなければ空 | $O(n + m)$ |
connected_components(g) |
無向 | 連結成分ごとの頂点のリスト | $O(n + m)$ |
is_connected(g) |
無向 | 連結か | $O(n + m)$ |
is_tree(g) |
無向 | 木か | $O(n + m)$ |
topological_sort(g) |
有向 | トポロジカル順に並べた頂点のリスト。DAG でなければ長さが n 未満になる |
$O(n + m)$ |
has_cycle(g) |
有向 | 閉路を持つか | $O(n + m)$ |
minimum_steiner_tree(g, X, inf = -1) |
無向 | 頂点集合 X をすべて含む部分木の辺の重みの総和の最小値 |
$O(3^k n + 2^k m \log m)$ ($k = \lvert X \rvert$) |
#pragma once
/**
* @file graph_util.hpp
* @brief グラフに関する関数
*/
#include <functional>
#include <queue>
#include <stack>
#include <utility>
#include <vector>
#include "graph.hpp"
/**
* @brief 無向グラフについて、二部グラフなら0と1に彩色した結果をひとつ返し、二部グラフでないなら空のvectorを返す。
* 連結成分のうち、インデックスの最も小さいものを0にする。
* @return std::vector<int> 各頂点の彩色結果
*/
template <typename Cost = int>
std::vector<int> bipartite_coloring(const Graph<Cost>& graph) {
std::vector<int> color(graph.n, -1);
for (int i = 0; i < graph.n; i++) {
if (color[i] != -1) continue;
std::stack<int> stk;
stk.push(i);
color[i] = 0;
while (!stk.empty()) {
int u = stk.top();
stk.pop();
for (int v : graph[u]) {
if (color[v] == -1) {
color[v] = color[u] ^ 1;
stk.push(v);
} else {
if (color[u] == color[v]) return {};
}
}
}
}
return color;
}
/**
* @brief 無向グラフについて、二部グラフかどうかを判定する。
* @return bool 二部グラフならtrue、二部グラフでないならfalseを返す。
*/
template <typename Cost = int>
bool is_bipartite(const Graph<Cost>& graph) {
return !bipartite_coloring(graph).empty();
}
/**
* @brief 無向グラフについて、連結成分分解する。
* @return std::vector<std::vector<int>> 「同じ連結成分となる頂点のリスト」のリスト
*/
template <typename Cost = int>
std::vector<std::vector<int>> connected_components(const Graph<Cost>& graph) {
std::vector<std::vector<int>> groups;
std::vector<bool> visited(graph.n);
for (int i = 0; i < graph.n; i++) {
if (visited[i]) continue;
std::stack<int> stk;
stk.push(i);
visited[i] = true;
groups.push_back({i});
while (!stk.empty()) {
int u = stk.top();
stk.pop();
for (int v : graph[u]) {
if (visited[v]) continue;
visited[v] = true;
stk.push(v);
groups.back().push_back(v);
}
}
}
return groups;
}
/**
* @brief 無向グラフについて、連結グラフかどうかを判定する。
* @return bool 連結グラフならtrue、連結グラフでないならfalseを返す。
*/
template <typename Cost = int>
bool is_connected(const Graph<Cost>& graph) {
return connected_components(graph).size() == 1;
}
/**
* @brief 無向グラフについて、木かどうかを判定する。
* @return bool 木ならtrue、木でないならfalseを返す。
*/
template <typename Cost = int>
bool is_tree(const Graph<Cost>& graph) {
return graph.m == graph.n - 1 && is_connected(graph);
}
/**
* @brief 有向グラフをトポロジカルソートする
* @param G トポロジカルソートするグラフ
* @return ソートされたノード番号のvector DAGでなければ長さがG.n未満になる
*/
template <typename Cost>
std::vector<int> topological_sort(const Graph<Cost>& G) {
std::vector<int> indeg(G.n), sorted;
std::queue<int> q;
for (int i = 0; i < G.n; i++) {
for (int dst : G[i]) indeg[dst]++;
}
for (int i = 0; i < G.n; i++) {
if (!indeg[i]) q.push(i);
}
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int dst : G[cur]) {
if (!--indeg[dst]) q.push(dst);
}
sorted.push_back(cur);
}
return sorted;
}
/**
* @brief 有向グラフについて、サイクルをもつかどうかを判定する。
* @return bool サイクルをもつならtrue、非巡回ならfalseを返す。
*/
template <typename Cost = int>
bool has_cycle(const Graph<Cost>& graph) {
return (int)topological_sort(graph).size() < graph.n;
}
/**
* @deprecated has_cycle を使うこと(名前と意味が逆に読めるため改名した)
*/
template <typename Cost = int>
[[deprecated("use has_cycle")]] bool has_acyclic(const Graph<Cost>& graph) {
return has_cycle(graph);
}
/**
* @brief 最小シュタイナー木の辺重みの総和
*/
template <typename Cost, typename T>
Cost minimum_steiner_tree(const Graph<Cost>& G, const std::vector<T>& X, Cost inf = -1) {
if (X.empty()) return Cost{};
std::vector<std::vector<Cost>> dp(G.n, std::vector<Cost>(1 << X.size(), inf));
for (int p = 0; p < (int)X.size(); p++) dp[X[p]][1 << p] = {};
for (int i = 0; i < (1 << X.size()); i++) {
for (int j = i; j > 0; j = (j - 1) & i) {
for (int k = 0; k < G.n; k++) {
if (dp[k][j] != inf && dp[k][i ^ j] != inf) {
if (dp[k][i] == inf || dp[k][i] > dp[k][j] + dp[k][i ^ j]) dp[k][i] = dp[k][j] + dp[k][i ^ j];
}
}
}
std::priority_queue<std::pair<Cost, int>, std::vector<std::pair<Cost, int>>, std::greater<std::pair<Cost, int>>> que;
for (int k = 0; k < G.n; k++)
if (dp[k][i] != inf) que.emplace(dp[k][i], k);
while (que.size()) {
auto [d, u] = que.top();
que.pop();
if (d > dp[u][i]) continue;
for (auto e : G[u]) {
if (dp[e.dst][i] == inf || dp[e.dst][i] > d + e.cost) {
dp[e.dst][i] = d + e.cost;
que.emplace(d + e.cost, e.dst);
}
}
}
}
Cost res = inf;
for (int k = 0; k < G.n; k++) {
if (dp[k].back() != inf && (res == inf || res > dp[k].back())) res = dp[k].back();
}
return res;
}#line 2 "src/graph/graph_util.hpp"
/**
* @file graph_util.hpp
* @brief グラフに関する関数
*/
#include <functional>
#include <queue>
#include <stack>
#include <utility>
#include <vector>
#line 2 "src/graph/graph.hpp"
/**
* @file graph.hpp
* @brief グラフ
*/
#include <algorithm>
#include <cassert>
#include <iostream>
#include <limits>
#line 14 "src/graph/graph.hpp"
/**
* @brief グラフの汎用クラス
*
* @tparam Cost 辺のコストの型
*/
template <typename Cost = int>
struct Graph {
/**
* @brief 有向辺の構造体
*
* operator int()を定義しているので、int型にキャストすると勝手にdstになる
* 例えば、
* for (auto& e : g[v]) をすると、vから出る辺が列挙されるが、
* for (int dst : g[v]) とすると、vから出る辺の行き先が列挙される
*/
struct Edge {
int src = -1; //!< 始点
int dst = -1; //!< 終点
Cost cost = {}; //!< コスト
int id = -1; //!< 辺の番号(追加された順、無向辺の場合はidが同じで方向が逆のものが2つ存在する)
Edge() = default;
Edge(int src, int dst, Cost cost = 1, int id = -1) : src(src), dst(dst), cost(cost), id(id) {}
operator int() const { return dst; }
};
/**
* @brief 最短路の結果
*
* auto [dist, prev] = g.shortest_path(s); のように受け取れる
*/
struct ShortestPath {
std::vector<Cost> dist; //!< 各頂点への最短路長
std::vector<Edge> prev; //!< 各頂点への最短路上の直前の辺 (始点と未到達の頂点では src == -1)
/**
* @brief 始点から t への最短路を構成する辺のリスト (始点側から順に)
* @note t が始点か未到達の頂点なら空。負閉路の影響を受ける頂点では最短路が定まらない (assert で落ちる)
*/
std::vector<Edge> path(int t) const {
std::vector<Edge> res;
while (prev[t].src != -1) {
res.push_back(prev[t]);
assert(res.size() < prev.size() && "path: negative cycle");
t = prev[t].src;
}
std::reverse(res.begin(), res.end());
return res;
}
};
int n; //!< 頂点数
int m; //!< 辺数
std::vector<std::vector<Edge>> g; //!< グラフの隣接リスト表現
/**
* @brief デフォルトコンストラクタ
*/
Graph() : n(0), m(0), g(0) {}
/**
* @brief コンストラクタ
* @param n 頂点数
*/
explicit Graph(int n) : n(n), m(0), g(n) {}
/**
* @brief 無向辺を追加する
* @param u 始点
* @param v 終点
* @param w コスト 省略したら1
*/
void add_edge(int u, int v, Cost w = 1) {
g[u].push_back({u, v, w, m});
g[v].push_back({v, u, w, m++});
}
/**
* @brief 有向辺を追加する
* @param u 始点
* @param v 終点
* @param w コスト 省略したら1
*/
void add_directed_edge(int u, int v, Cost w = 1) {
g[u].push_back({u, v, w, m++});
}
/**
* @brief 辺の情報を標準入力から受け取って追加する
* @param m 辺の数
* @param padding 頂点番号を入力からいくつずらすか 省略したら-1
* @param weighted 辺の重みが入力されるか 省略したらfalseとなり、重み1で辺が追加される
* @param directed 有向グラフかどうか 省略したらfalse
*/
void read(int m, int padding = -1, bool weighted = false, bool directed = false) {
for (int i = 0; i < m; i++) {
int u, v;
std::cin >> u >> v;
u += padding, v += padding;
Cost c(1);
if (weighted)
std::cin >> c;
if (directed)
add_directed_edge(u, v, c);
else
add_edge(u, v, c);
}
}
/**
* @brief ある頂点から出る辺を列挙する
* @param v 頂点番号
* @return std::vector<Edge>& vから出る辺のリスト
*/
std::vector<Edge> &operator[](int v) {
return g[v];
}
/**
* @brief ある頂点から出る辺を列挙する
* @param v 頂点番号
* @return const std::vector<Edge>& vから出る辺のリスト
*/
const std::vector<Edge> &operator[](int v) const {
return g[v];
}
/**
* @brief 辺のリスト
* @return std::vector<Edge> 辺のリスト(idの昇順)
*
* 無向辺は代表して1つだけ格納される
*/
std::vector<Edge> edges() const {
std::vector<Edge> res(m);
for (int i = 0; i < n; i++) {
for (auto &e : g[i]) {
res[e.id] = e;
}
}
return res;
}
/**
* @brief ある頂点から各頂点への最短路
*
* @param s 始点
* @param weighted 1以外のコストの辺が存在するか 省略するとtrue
* @param inf コストのminの単位元 未到達の頂点への距離はinfになる 省略すると
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
*/
ShortestPath shortest_path(int s, bool weighted = true, Cost inf = -1) const {
if (weighted)
return shortest_path_dijkstra(s, inf);
return shortest_path_bfs(s, inf);
}
/**
* @brief ある頂点から各頂点への最短路
*
* @param s 始点
* @param inf コストのminの単位元 未到達の頂点への距離はinfになる 省略すると std::numeric_limits<Cost>::max() / 4 負閉路の影響を受ける点は -inf
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
*/
ShortestPath bellman_ford(int s, Cost inf = std::numeric_limits<Cost>::max() / 4) const {
std::vector<Cost> dist(n, inf);
std::vector<Edge> prev(n);
dist[s] = Cost{};
for (int i = 1; i < n; i++) {
bool changed = false;
for (int j = 0; j < n; j++)
for (const auto &e : g[j]) {
if (dist[e.src] == inf)
continue;
if (dist[e.dst] > dist[e.src] + e.cost) {
dist[e.dst] = dist[e.src] + e.cost;
if (dist[e.dst] < -inf)
dist[e.dst] = -inf;
prev[e.dst] = e;
changed = true;
}
}
if (!changed)
break;
}
for (int i = 0; i < n; i++) {
bool changed = false;
for (int j = 0; j < n; j++)
for (const auto &e : g[j]) {
if (dist[e.src] == inf)
continue;
if (dist[e.dst] > dist[e.src] + e.cost) {
dist[e.dst] = -inf;
prev[e.dst] = e;
changed = true;
}
}
if (!changed)
break;
}
return {dist, prev};
}
private:
ShortestPath shortest_path_bfs(int s, Cost inf) const {
std::vector<Cost> dist(n, inf);
std::vector<Edge> prev(n);
std::queue<int> que;
dist[s] = 0;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
for (auto &e : g[u]) {
if (dist[e.dst] == inf) {
dist[e.dst] = dist[e.src] + 1;
prev[e.dst] = e;
que.push(e.dst);
}
}
}
return {dist, prev};
}
ShortestPath shortest_path_dijkstra(int s, Cost inf) const {
std::vector<Cost> dist(n, inf);
std::vector<Edge> prev(n);
using Node = std::pair<Cost, int>;
std::priority_queue<Node, std::vector<Node>, std::greater<Node>> que;
dist[s] = 0;
que.push({0, s});
while (!que.empty()) {
auto [d, u] = que.top();
que.pop();
if (d > dist[u])
continue;
for (auto &e : g[u]) {
if (dist[e.dst] == inf || dist[e.dst] > dist[e.src] + e.cost) {
dist[e.dst] = dist[e.src] + e.cost;
prev[e.dst] = e;
que.push({dist[e.dst], e.dst});
}
}
}
return {dist, prev};
}
};
#line 15 "src/graph/graph_util.hpp"
/**
* @brief 無向グラフについて、二部グラフなら0と1に彩色した結果をひとつ返し、二部グラフでないなら空のvectorを返す。
* 連結成分のうち、インデックスの最も小さいものを0にする。
* @return std::vector<int> 各頂点の彩色結果
*/
template <typename Cost = int>
std::vector<int> bipartite_coloring(const Graph<Cost>& graph) {
std::vector<int> color(graph.n, -1);
for (int i = 0; i < graph.n; i++) {
if (color[i] != -1) continue;
std::stack<int> stk;
stk.push(i);
color[i] = 0;
while (!stk.empty()) {
int u = stk.top();
stk.pop();
for (int v : graph[u]) {
if (color[v] == -1) {
color[v] = color[u] ^ 1;
stk.push(v);
} else {
if (color[u] == color[v]) return {};
}
}
}
}
return color;
}
/**
* @brief 無向グラフについて、二部グラフかどうかを判定する。
* @return bool 二部グラフならtrue、二部グラフでないならfalseを返す。
*/
template <typename Cost = int>
bool is_bipartite(const Graph<Cost>& graph) {
return !bipartite_coloring(graph).empty();
}
/**
* @brief 無向グラフについて、連結成分分解する。
* @return std::vector<std::vector<int>> 「同じ連結成分となる頂点のリスト」のリスト
*/
template <typename Cost = int>
std::vector<std::vector<int>> connected_components(const Graph<Cost>& graph) {
std::vector<std::vector<int>> groups;
std::vector<bool> visited(graph.n);
for (int i = 0; i < graph.n; i++) {
if (visited[i]) continue;
std::stack<int> stk;
stk.push(i);
visited[i] = true;
groups.push_back({i});
while (!stk.empty()) {
int u = stk.top();
stk.pop();
for (int v : graph[u]) {
if (visited[v]) continue;
visited[v] = true;
stk.push(v);
groups.back().push_back(v);
}
}
}
return groups;
}
/**
* @brief 無向グラフについて、連結グラフかどうかを判定する。
* @return bool 連結グラフならtrue、連結グラフでないならfalseを返す。
*/
template <typename Cost = int>
bool is_connected(const Graph<Cost>& graph) {
return connected_components(graph).size() == 1;
}
/**
* @brief 無向グラフについて、木かどうかを判定する。
* @return bool 木ならtrue、木でないならfalseを返す。
*/
template <typename Cost = int>
bool is_tree(const Graph<Cost>& graph) {
return graph.m == graph.n - 1 && is_connected(graph);
}
/**
* @brief 有向グラフをトポロジカルソートする
* @param G トポロジカルソートするグラフ
* @return ソートされたノード番号のvector DAGでなければ長さがG.n未満になる
*/
template <typename Cost>
std::vector<int> topological_sort(const Graph<Cost>& G) {
std::vector<int> indeg(G.n), sorted;
std::queue<int> q;
for (int i = 0; i < G.n; i++) {
for (int dst : G[i]) indeg[dst]++;
}
for (int i = 0; i < G.n; i++) {
if (!indeg[i]) q.push(i);
}
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int dst : G[cur]) {
if (!--indeg[dst]) q.push(dst);
}
sorted.push_back(cur);
}
return sorted;
}
/**
* @brief 有向グラフについて、サイクルをもつかどうかを判定する。
* @return bool サイクルをもつならtrue、非巡回ならfalseを返す。
*/
template <typename Cost = int>
bool has_cycle(const Graph<Cost>& graph) {
return (int)topological_sort(graph).size() < graph.n;
}
/**
* @deprecated has_cycle を使うこと(名前と意味が逆に読めるため改名した)
*/
template <typename Cost = int>
[[deprecated("use has_cycle")]] bool has_acyclic(const Graph<Cost>& graph) {
return has_cycle(graph);
}
/**
* @brief 最小シュタイナー木の辺重みの総和
*/
template <typename Cost, typename T>
Cost minimum_steiner_tree(const Graph<Cost>& G, const std::vector<T>& X, Cost inf = -1) {
if (X.empty()) return Cost{};
std::vector<std::vector<Cost>> dp(G.n, std::vector<Cost>(1 << X.size(), inf));
for (int p = 0; p < (int)X.size(); p++) dp[X[p]][1 << p] = {};
for (int i = 0; i < (1 << X.size()); i++) {
for (int j = i; j > 0; j = (j - 1) & i) {
for (int k = 0; k < G.n; k++) {
if (dp[k][j] != inf && dp[k][i ^ j] != inf) {
if (dp[k][i] == inf || dp[k][i] > dp[k][j] + dp[k][i ^ j]) dp[k][i] = dp[k][j] + dp[k][i ^ j];
}
}
}
std::priority_queue<std::pair<Cost, int>, std::vector<std::pair<Cost, int>>, std::greater<std::pair<Cost, int>>> que;
for (int k = 0; k < G.n; k++)
if (dp[k][i] != inf) que.emplace(dp[k][i], k);
while (que.size()) {
auto [d, u] = que.top();
que.pop();
if (d > dp[u][i]) continue;
for (auto e : G[u]) {
if (dp[e.dst][i] == inf || dp[e.dst][i] > d + e.cost) {
dp[e.dst][i] = d + e.cost;
que.emplace(d + e.cost, e.dst);
}
}
}
}
Cost res = inf;
for (int k = 0; k < G.n; k++) {
if (dp[k].back() != inf && (res == inf || res > dp[k].back())) res = dp[k].back();
}
return res;
}