競技プログラミング用の C++ ライブラリ
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_C"
// shortest_path_floyd_warshall を使う
#include <iostream>
#include <limits>
#include "../../../src/graph/shortest-path.hpp"
int main() {
int n, m;
std::cin >> n >> m;
Graph<long long> g(n);
g.read(m, 0, true, true);
const long long inf = std::numeric_limits<long long>::max() / 4;
auto d = shortest_path_floyd_warshall(g, inf);
for (int i = 0; i < n; i++) {
if (d[i][i] < 0) {
std::cout << "NEGATIVE CYCLE" << '\n';
return 0;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j) std::cout << ' ';
if (d[i][j] == inf)
std::cout << "INF";
else
std::cout << d[i][j];
}
std::cout << '\n';
}
}#line 1 "test/aoj/grl/grl-1-c.2.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_C"
// shortest_path_floyd_warshall を使う
#include <iostream>
#include <limits>
#line 2 "src/graph/shortest-path.hpp"
/**
* @file shortest-path.hpp
* @brief 最短路
*/
#include <algorithm>
#include <cassert>
#include <deque>
#include <functional>
#line 13 "src/graph/shortest-path.hpp"
#include <optional>
#include <queue>
#include <utility>
#include <vector>
#line 2 "src/graph/graph.hpp"
/**
* @file graph.hpp
* @brief グラフ
*/
#line 12 "src/graph/graph.hpp"
/**
* @brief グラフの汎用クラス
*
* @tparam Cost 辺のコストの型 省略したら long long (重みの和や未到達を表す max / 4 があふれにくいように)
*/
template <typename Cost = long long>
class Graph {
public:
/**
* @brief 有向辺の構造体
*
* operator long long()を定義しているので、整数型にキャストすると勝手にdstになる
* 例えば、
* for (auto& e : g[v]) をすると、vから出る辺が列挙されるが、
* for (long long dst : g[v]) とすると、vから出る辺の行き先が列挙される
*/
struct Edge {
long long src = -1; //!< 始点
long long dst = -1; //!< 終点
Cost cost = {}; //!< コスト
long long id = -1; //!< 辺の番号(追加された順、無向辺の場合はidが同じで方向が逆のものが2つ存在する)
Edge() = default;
Edge(long long src, long long dst, Cost cost = 1, long long id = -1) : src(src), dst(dst), cost(cost), id(id) {}
operator long long() const { return dst; }
};
private:
long long n; //!< 頂点数
long long m; //!< 辺数
std::vector<std::vector<Edge>> g; //!< グラフの隣接リスト表現
public:
/**
* @brief デフォルトコンストラクタ
*/
Graph() : n(0), m(0), g(0) {}
/**
* @brief コンストラクタ
* @param n 頂点数
*/
explicit Graph(long long n) : n(n), m(0), g(n) {}
/**
* @brief 頂点数
*/
long long size() const { return n; }
/**
* @brief 辺数 (無向辺は 1 本と数える)
*/
long long edge_count() const { return m; }
/**
* @brief 無向辺を追加する
* @param u 始点
* @param v 終点
* @param w コスト 省略したら1
*/
void add_edge(long long u, long long v, Cost w = 1) {
assert(0 <= u && u < n && 0 <= v && v < n);
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(long long u, long long v, Cost w = 1) {
assert(0 <= u && u < n && 0 <= v && v < n);
g[u].push_back({u, v, w, m++});
}
/**
* @brief 辺の情報を標準入力から受け取って追加する
* @param m 辺の数
* @param padding 頂点番号を入力からいくつずらすか 省略したら-1
* @param weighted 辺の重みが入力されるか 省略したらfalseとなり、重み1で辺が追加される
* @param directed 有向グラフかどうか 省略したらfalse
*/
void read(long long m, long long padding = -1, bool weighted = false, bool directed = false) {
for (long long i = 0; i < m; i++) {
long long 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 const std::vector<Edge>& vから出る辺のリスト
*/
const std::vector<Edge>& operator[](long long v) const {
assert(0 <= v && v < n);
return g[v];
}
/**
* @brief 辺のリスト
* @return std::vector<Edge> 辺のリスト(idの昇順)
*
* 無向辺は代表して1つだけ格納される。その src と dst の向きは規定しない
* 有向辺は追加したときの向きのまま格納される
*/
std::vector<Edge> edges() const {
std::vector<Edge> res(m);
for (long long i = 0; i < n; i++) {
for (auto& e : g[i]) {
res[e.id] = e;
}
}
return res;
}
};
/**
* @brief 経路 (路・閉路)。長さ cost、たどる頂点の列 vertices、たどる辺の列 edges
*
* edges[k] は vertices[k] から vertices[k + 1] へ向かう (edges[k].src == vertices[k]、edges[k].dst == vertices[k + 1])
* vertices は edges より 1 つ多い。辺がなくても始点 1 つが入る。閉路なら vertices.front() == vertices.back()
* auto [cost, vertices, edges] = *shortest_path(g, s, t); のように受け取れる
*/
template <typename Cost>
struct Path {
Cost cost; //!< 長さ (辺のコストの和)
std::vector<long long> vertices; //!< たどる頂点 (始点から順に)
std::vector<typename Graph<Cost>::Edge> edges; //!< たどる辺 (始点側から順に)
};
namespace internal_graph {
/**
* @brief 始点 s と、s からたどる順に並べた辺 edges から Path を作る。cost は辺のコストの和
*/
template <typename Cost>
Path<Cost> make_path(long long s, std::vector<typename Graph<Cost>::Edge> edges) {
Path<Cost> res{Cost{}, {s}, std::move(edges)};
for (const auto& e : res.edges) {
assert(e.src == res.vertices.back());
res.cost += e.cost;
res.vertices.push_back(e.dst);
}
return res;
}
} // namespace internal_graph
#line 19 "src/graph/shortest-path.hpp"
/**
* @brief 1 点から全点への最短路の結果
*
* auto [dist, prev] = shortest_path_dijkstra(g, s); のように受け取れる
*/
template <typename Cost>
struct ShortestPath {
using Edge = typename Graph<Cost>::Edge;
std::vector<Cost> dist; //!< 各頂点への最短路長
std::vector<Edge> prev; //!< 各頂点への最短路上の直前の辺 (始点と未到達の頂点では src == -1)
/**
* @brief 始点から t への最短路 (長さ、たどる頂点、たどる辺)
* cost は dist[t] (shortest_path_bfs では辺の本数)
* @return std::optional<Path<Cost>> t が始点なら長さ 0、頂点は t だけ、辺は空。未到達なら std::nullopt
* @note 負閉路の影響を受ける頂点では最短路が定まらない (assert で落ちる)
*/
std::optional<Path<Cost>> path(long long t) const {
// 直前の辺がないのは始点と未到達の頂点。始点の距離は 0 で、未到達の距離 inf は正なので区別できる
if (prev[t].src == -1 && dist[t] != Cost{}) return std::nullopt;
Path<Cost> res{dist[t], {t}, {}};
while (prev[t].src != -1) {
res.edges.push_back(prev[t]);
assert(res.edges.size() < prev.size() && "path: negative cycle");
t = prev[t].src;
res.vertices.push_back(t);
}
std::reverse(res.vertices.begin(), res.vertices.end());
std::reverse(res.edges.begin(), res.edges.end());
return res;
}
};
namespace internal_shortest_path {
template <typename Cost>
ShortestPath<Cost> bfs(const Graph<Cost>& graph, long long s, Cost inf) {
std::vector<Cost> dist(graph.size(), inf);
std::vector<typename Graph<Cost>::Edge> prev(graph.size());
std::queue<long long> que;
dist[s] = 0;
que.push(s);
while (!que.empty()) {
long long u = que.front();
que.pop();
for (auto& e : graph[u]) {
if (dist[e.dst] == inf) {
dist[e.dst] = dist[e.src] + 1;
prev[e.dst] = e;
que.push(e.dst);
}
}
}
return {dist, prev};
}
// target が -1 でなければ、target の距離が決まった時点で打ち切る
template <typename Cost>
ShortestPath<Cost> dijkstra(const Graph<Cost>& graph, long long s, Cost inf, long long target = -1) {
for (long long v = 0; v < graph.size(); v++) {
for (const auto& e : graph[v]) assert(!(e.cost < Cost{}) && "negative edge (use shortest_path_bellman_ford)");
}
std::vector<Cost> dist(graph.size(), inf);
std::vector<typename Graph<Cost>::Edge> prev(graph.size());
using Node = std::pair<Cost, long long>;
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;
if (u == target) break;
for (auto& e : graph[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};
}
} // namespace internal_shortest_path
/**
* @brief s から t への最短路 (Dijkstra。t の距離が決まった時点で打ち切る) O(m log m)
*
* @return std::optional<Path<Cost>> 長さ、たどる頂点、たどる辺。届かなければ std::nullopt。s == t なら長さ 0、頂点は s だけ、辺は空
* @note 負の辺があると assert で落ちる (負の辺があるなら shortest_path_bellman_ford)
*/
template <typename Cost = long long>
std::optional<Path<Cost>> shortest_path(const Graph<Cost>& graph, long long s, long long t) {
assert(0 <= s && s < graph.size());
assert(0 <= t && t < graph.size());
return internal_shortest_path::dijkstra(graph, s, std::numeric_limits<Cost>::max() / 4, t).path(t);
}
/**
* @brief ある頂点から各頂点への最短路 (Dijkstra) O(m log m)
*
* @param s 始点
* @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
* @note 負の辺があると assert で落ちる (負の辺があるなら shortest_path_bellman_ford)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_dijkstra(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
return internal_shortest_path::dijkstra(graph, s, inf);
}
/**
* @brief 辺の重みをすべて 1 とみなして、ある頂点から各頂点への最短路 (BFS) O(n + m)
*
* @param s 始点
* @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
* @return ShortestPath 各頂点への最短路長 (辺の本数、dist) と、各頂点への最短路上の直前の辺 (prev)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_bfs(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
return internal_shortest_path::bfs(graph, s, inf);
}
/**
* @brief ある頂点から各頂点への最短路
*
* @param s 始点
* @param inf コストのminの単位元 未到達の頂点への距離はinfになる 省略すると std::numeric_limits<Cost>::max() / 4 負閉路の影響を受ける点は -inf
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_bellman_ford(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
const long long n = graph.size();
std::vector<Cost> dist(n, inf);
std::vector<typename Graph<Cost>::Edge> prev(n);
dist[s] = Cost{};
for (long long i = 1; i < n; i++) {
bool changed = false;
for (long long j = 0; j < n; j++)
for (const auto& e : graph[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 (long long i = 0; i < n; i++) {
bool changed = false;
for (long long j = 0; j < n; j++)
for (const auto& e : graph[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};
}
/**
* @brief 辺のコストが 0 か 1 だけのグラフで、ある頂点から各頂点への最短路 (01-BFS) O(n + m)
*
* @param s 始点
* @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_01bfs(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
std::vector<Cost> dist(graph.size(), inf);
std::vector<typename Graph<Cost>::Edge> prev(graph.size());
std::deque<long long> que;
dist[s] = 0;
que.push_back(s);
while (!que.empty()) {
long long u = que.front();
que.pop_front();
for (auto& e : graph[u]) {
assert(e.cost == 0 || e.cost == 1);
if (dist[e.dst] == inf || dist[e.dst] > dist[u] + e.cost) {
dist[e.dst] = dist[u] + e.cost;
prev[e.dst] = e;
if (e.cost == 0)
que.push_front(e.dst);
else
que.push_back(e.dst);
}
}
}
return {dist, prev};
}
/**
* @brief 全点対間の最短路長 (Floyd-Warshall) O(n^3)
*
* @param inf 未到達を表す値 省略すると std::numeric_limits<Cost>::max() / 4
* @return std::vector<std::vector<Cost>> dist[i][j] が i から j への最短路長 (到達できなければ inf)
* @note 負の辺があってもよい。dist[i][i] < 0 となる i があれば負閉路がある
* 負閉路があるときの値は -inf 以上に切り詰めるので、あふれない (負閉路の影響を受ける組の値は最短路長ではない)
*/
template <typename Cost = long long>
std::vector<std::vector<Cost>> shortest_path_floyd_warshall(const Graph<Cost>& graph, Cost inf = std::numeric_limits<Cost>::max() / 4) {
const long long n = graph.size();
std::vector<std::vector<Cost>> dist(n, std::vector<Cost>(n, inf));
for (long long i = 0; i < n; i++) dist[i][i] = Cost{};
for (long long i = 0; i < n; i++) {
for (auto& e : graph[i]) dist[i][e.dst] = std::min(dist[i][e.dst], e.cost);
}
for (long long k = 0; k < n; k++) {
for (long long i = 0; i < n; i++) {
if (dist[i][k] == inf) continue;
for (long long j = 0; j < n; j++) {
if (dist[k][j] == inf) continue;
// dist は -inf 以上 inf 以下なので、和は -2 inf 以上であふれない
Cost d = dist[i][k] + dist[k][j];
if (d < -inf) d = -inf;
if (d < dist[i][j]) dist[i][j] = d;
}
}
}
return dist;
}
#line 9 "test/aoj/grl/grl-1-c.2.test.cpp"
int main() {
int n, m;
std::cin >> n >> m;
Graph<long long> g(n);
g.read(m, 0, true, true);
const long long inf = std::numeric_limits<long long>::max() / 4;
auto d = shortest_path_floyd_warshall(g, inf);
for (int i = 0; i < n; i++) {
if (d[i][i] < 0) {
std::cout << "NEGATIVE CYCLE" << '\n';
return 0;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j) std::cout << ' ';
if (d[i][j] == inf)
std::cout << "INF";
else
std::cout << d[i][j];
}
std::cout << '\n';
}
}