競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
有向グラフの距離行列から、全点対最短距離と負閉路の影響を求めます。 中継頂点を順に追加して距離を更新します。
V=頂点数、L=返す経路の頂点数です。
FloydWarshallinline bool FloydWarshall(std::vector<std::vector<std::int64_t>> &distances, std::int64_t inf = (std::int64_t{1} << 60));
inline bool FloydWarshall(std::vector<std::vector<std::int64_t>> &distances, std::vector<std::vector<int>> &next, std::int64_t inf = (std::int64_t{1} << 60));
距離行列を全点対の最短距離で上書きし、負閉路があればtrueを返します。次頂点表nextを指定すると、その表も作ります。
制約: 行列・番兵・有限距離の前提は下記の通りです。
計算量: O(V³)時間。追加領域は通常O(V)。より広い範囲の整数演算を使う場合や、次頂点表を作る版ではO(V²)。
FloydWarshallPathinline std::vector<int> FloydWarshallPath(const std::vector<std::vector<int>> &next, int from, int to);
経路の頂点列を返します。到達できない場合や負閉路の影響がある場合は空です。
制約: distanceは正方行列。nextには本関数で作った表を渡し、from/toは有効な頂点番号です。
計算量: O(L+1)時間・領域。
distanceはstd::vector<std::vector<std::int64_t>>の正方行列です。
正のstd::int64_t infを未接続値として指定し、省略時はkInf = std::int64_t{1} << 60を使います。
入力行列も同じinfで初期化してください。有限重みは(-inf, inf)で、対角は入力値と0の小さい方を使います。
出力は未到達がinf、負閉路を経由して到達できる組だけが-infになります。
const std::int64_t inf = 1'000'000'000'000;
std::vector distance(4, std::vector<std::int64_t>(4, inf));
distance[0][1] = 4;
distance[1][2] = -2;
std::vector<std::vector<int>> next;
const bool negative = FloydWarshall(distance, next, inf);
auto path = FloydWarshallPath(next, 0, 2);
// negative=false, distance[0][2]=2, path={0,1,2}
// distance[0][3]=inf、distance[i][i]=0
頂点数はINT_MAX以下とし、nextはこの関数で作った表を渡します。
有限な最短距離が(-inf, inf)を外れる場合はoverflow_errorです。
負閉路の影響による-infとは区別します。途中の和だけが範囲外でも、答えが範囲内なら正常に返ります。
inf<=0はinvalid_argument、容量超過はlength_errorです。
既定では行列の形状・入力値・経路復元の頂点を検査します。
不正な形状はinvalid_argument、値や頂点はout_of_rangeです。
SKIP_RUNTIME_CHECKSで入力検査を省く場合も、容量・算術範囲・infの正値の保護は維持します。
例外時の距離行列の内容は未規定です。
時間O(V³)、通常版の追加領域O(V)、大きな重みで広幅演算が必要な場合はO(V²)です。 経路版はさらにO(V²)の表を作り、経路復元はO(L+1)時間・領域です。 既定の番兵では対応CPU上でSIMDを使う場合があります。無効化はSIMDの指定を参照してください。
Verify先はABC012 Dです。 負辺・負閉路・未到達・経路復元・大きな重みとカスタム番兵は独立参照でも照合します。
kInf=std::int64_t{1}<<60。
[Floyd-Warshall] V=頂点数、L=返す経路の頂点数。
FloydWarshall(distances, inf=2^60): 正方行列を全点対最短距離で上書きし、グラフ内に負閉路があればtrue。O(V^3)時間。追加領域は下記。
FloydWarshall(distances, next, inf=2^60): 次頂点表nextも作る。O(V^3)時間・O(V^2)追加領域。
FloydWarshallPath(next, from, to): 次頂点表から頂点列をO(L+1)時間・領域で復元。未到達・負閉路の影響下なら空。
入力はinf>0が未接続、有限重みは(-inf, inf)。対角はmin(入力, 0)とする。
出力は未到達inf、負閉路を経由できる組だけ-inf。有限距離が(-inf, inf)外ならoverflow_error。
算術範囲の算出を兼ねて初期行列を走査する。SKIP_RUNTIME_CHECKSで形状・入力値・頂点の検査を除く。
通常版の追加領域はO(V)。大きな重みで広幅演算が必要な場合はO(V^2)。例外時の行列の内容は未規定。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Typical Shortest Path Sum (FloydWarshall) | coverage_graph_floyd_warshall_all_pairs_yuki.cpp | 未提出 | — |
| D - バスと避けられない運命 | floyd_warshall.cpp | 現行未照合・要再提出 | AC |
| 独立参照による補足検査 | graph_local.cpp | ローカル補足 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// 参考: https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/viewer/floyd-warshall
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/floyd_warshall.md
//
// API一覧
// kInf=std::int64_t{1}<<60。
// [Floyd-Warshall] V=頂点数、L=返す経路の頂点数。
// FloydWarshall(distances, inf=2^60): 正方行列を全点対最短距離で上書きし、グラフ内に負閉路があればtrue。O(V^3)時間。追加領域は下記。
// FloydWarshall(distances, next, inf=2^60): 次頂点表nextも作る。O(V^3)時間・O(V^2)追加領域。
// FloydWarshallPath(next, from, to): 次頂点表から頂点列をO(L+1)時間・領域で復元。未到達・負閉路の影響下なら空。
// 入力はinf>0が未接続、有限重みは(-inf, inf)。対角はmin(入力, 0)とする。
// 出力は未到達inf、負閉路を経由できる組だけ-inf。有限距離が(-inf, inf)外ならoverflow_error。
// 算術範囲の算出を兼ねて初期行列を走査する。SKIP_RUNTIME_CHECKSで形状・入力値・頂点の検査を除く。
// 通常版の追加領域はO(V)。大きな重みで広幅演算が必要な場合はO(V^2)。例外時の行列の内容は未規定。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <vector>
#include <type_traits>
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
#include <immintrin.h>
#endif
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_INF_DEFINED
#define SIRKIT_INF_DEFINED
inline constexpr std::int64_t kInf = std::int64_t{1} << 60;
#endif
#ifndef SIRKIT_FLOYD_WARSHALL_DEFINED
#define SIRKIT_FLOYD_WARSHALL_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
// boolは既存の実行経路、専用の列挙型は有限範囲のSIMD最適化を選ぶ。
enum class FloydWarshallSimdMode { Finite = 1 };
#if defined(__SIZEOF_INT128__) && (defined(__GNUC__) || defined(__clang__))
using FloydWarshallWide = __int128_t;
#else
// 必要なのは最大約92ビット。符号付き上位語と符号なし下位語で標準C++でも扱う。
struct FloydWarshallWide
{
std::int64_t high = 0;
std::uint64_t low = 0;
constexpr FloydWarshallWide() = default;
constexpr FloydWarshallWide(std::int64_t value)
: high(value < 0 ? -1 : 0), low(static_cast<std::uint64_t>(value)) {}
constexpr FloydWarshallWide(std::int64_t upper, std::uint64_t lower)
: high(upper), low(lower) {}
friend constexpr FloydWarshallWide operator+(FloydWarshallWide a,
FloydWarshallWide b)
{
const auto lower = a.low + b.low;
return {a.high + b.high + (lower < a.low), lower};
}
friend constexpr FloydWarshallWide operator-(FloydWarshallWide value)
{
const auto lower = std::uint64_t{0} - value.low;
return {~value.high + (lower == 0), lower};
}
friend constexpr bool operator<(FloydWarshallWide a, FloydWarshallWide b)
{
return a.high < b.high || (a.high == b.high && a.low < b.low);
}
friend constexpr bool operator==(FloydWarshallWide, FloydWarshallWide) = default;
explicit constexpr operator std::int64_t() const { return std::bit_cast<std::int64_t>(low); }
};
#endif
// 広幅実装でも下限の絶対値は単純路の最大絶対値より大きい。
inline FloydWarshallWide FloydWarshallLimit(std::size_t n)
{
#if defined(__SIZEOF_INT128__) && (defined(__GNUC__) || defined(__clang__))
return static_cast<FloydWarshallWide>(n) * kInf;
#else
return {static_cast<std::int64_t>(n >> 4), static_cast<std::uint64_t>(n) << 60};
#endif
}
// n<=INT_MAX、inf<=INT64_MAXなので積は94bit以内。標準経路も積を分割する。
inline FloydWarshallWide FloydWarshallCustomLimit(std::size_t n, std::int64_t inf)
{
#if defined(__SIZEOF_INT128__) && (defined(__GNUC__) || defined(__clang__))
return static_cast<FloydWarshallWide>(n) * inf;
#else
const auto value = static_cast<std::uint64_t>(inf);
const auto first = static_cast<std::uint64_t>(n) * (value & 0xffffffffu);
const auto second = static_cast<std::uint64_t>(n) * (value >> 32);
const auto low = first + (second << 32);
return {static_cast<std::int64_t>((second >> 32) + (low < first)), low};
#endif
}
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
template <bool RestorePath, bool HasNegative,
#if !defined(__clang__)
bool EncodeEligible,
#endif
bool Dense>
[[gnu::target("avx2")]]
inline void FloydWarshallRelaxAvx2(std::vector<std::vector<std::int64_t>> &distance,
std::int64_t unreachable, std::int64_t lower,
std::vector<std::vector<int>> *next)
{
const std::size_t n = distance.size();
#if !defined(__clang__)
if constexpr (EncodeEligible && !RestorePath && !HasNegative) {
if (n >= 64) {
constexpr std::int64_t bias = INT64_C(0x3ff0000000000000);
const __m256i v_bias = _mm256_set1_epi64x(bias);
// kInfに当たれば変換済みの先頭だけ戻して通常経路へ渡す。
const auto v_missing = _mm256_set1_epi64x(unreachable);
std::size_t encoded_rows = 0, encoded_columns = 0;
bool all_finite = true;
for (; encoded_rows < n; ++encoded_rows) {
auto* row = distance[encoded_rows].data();
encoded_columns = 0;
for (; encoded_columns + 4 <= n; encoded_columns += 4) {
const auto v = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(row + encoded_columns));
const auto missing = _mm256_cmpeq_epi64(v,v_missing);
if (!_mm256_testz_si256(missing,missing)) { all_finite = false; break; }
_mm256_storeu_si256(reinterpret_cast<__m256i*>(row + encoded_columns), _mm256_add_epi64(v,v_bias));
}
if (!all_finite) break;
for (; encoded_columns < n; ++encoded_columns) {
if (row[encoded_columns] == unreachable) { all_finite = false; break; }
row[encoded_columns] += bias;
}
if (!all_finite) break;
}
if (all_finite) {
encoded_columns = 0;
for (std::size_t via = 0; via < n; ++via) {
const auto* through = distance[via].data();
for (std::size_t from = 0; from < n; ++from) {
auto* row = distance[from].data();
const auto prefix = row[via] - bias;
if (prefix == unreachable) continue;
const auto v_prefix = _mm256_set1_epi64x(prefix);
std::size_t to = 0;
for (; to + 4 <= n; to += 4) {
const auto values = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(through + to));
const auto previous = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(row + to));
const auto candidate = _mm256_add_epi64(v_prefix, values);
const auto best = _mm256_min_pd(_mm256_castsi256_pd(previous), _mm256_castsi256_pd(candidate));
_mm256_storeu_si256(reinterpret_cast<__m256i*>(row + to), _mm256_castpd_si256(best));
}
for (; to < n; ++to) row[to] = std::min(row[to], prefix + through[to]);
}
}
}
const auto converted = encoded_rows + static_cast<std::size_t>(encoded_columns != 0);
for (std::size_t from = 0; from < converted; ++from) {
auto* row = distance[from].data();
const auto count = from < encoded_rows ? n : encoded_columns;
std::size_t to = 0;
for (; to + 4 <= count; to += 4) {
const auto v = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(row + to));
_mm256_storeu_si256(reinterpret_cast<__m256i*>(row + to), _mm256_sub_epi64(v,v_bias));
}
for (; to < count; ++to) row[to] -= bias;
}
if (all_finite) return;
}
}
#endif
const __m256i v_unreachable = _mm256_set1_epi64x(unreachable);
const __m256i v_lower = _mm256_set1_epi64x(lower);
for (std::size_t via = 0; via < n; ++via)
{
const auto *through = distance[via].data();
for (std::size_t from = 0; from < n; ++from)
{
auto *row = distance[from].data();
const auto prefix = row[via];
if (prefix == unreachable)
continue;
const __m256i v_prefix = _mm256_set1_epi64x(prefix);
int *path = nullptr;
int following = 0;
if constexpr (RestorePath)
{
path = (*next)[from].data();
following = path[via];
}
std::size_t to = 0;
for (; to + 4 <= n; to += 4)
{
const __m256i values = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(through + to));
const __m256i old = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(row + to));
__m256i candidate = _mm256_add_epi64(v_prefix, values);
if constexpr (HasNegative)
candidate = _mm256_blendv_epi8(candidate, v_lower, _mm256_cmpgt_epi64(v_lower, candidate));
__m256i improve = _mm256_cmpgt_epi64(old, candidate);
// 未到達laneの加算結果は捨て、到達済みのlaneだけ更新する。
if constexpr (!Dense)
improve = _mm256_andnot_si256(_mm256_cmpeq_epi64(values, v_unreachable), improve);
_mm256_storeu_si256(reinterpret_cast<__m256i *>(row + to), _mm256_blendv_epi8(old, candidate, improve));
if constexpr (RestorePath)
{
const __m128 lo = _mm_castsi128_ps(_mm256_castsi256_si128(improve));
const __m128 hi = _mm_castsi128_ps(_mm256_extracti128_si256(improve, 1));
const __m128i mask = _mm_castps_si128(_mm_shuffle_ps(lo, hi, _MM_SHUFFLE(2, 0, 2, 0)));
const __m128i previous = _mm_loadu_si128(reinterpret_cast<const __m128i *>(path + to));
_mm_storeu_si128(reinterpret_cast<__m128i *>(path + to),
_mm_blendv_epi8(previous, _mm_set1_epi32(following), mask));
}
}
for (; to < n; ++to)
{
if constexpr (!Dense)
if (through[to] == unreachable)
continue;
auto candidate = prefix + through[to];
if constexpr (HasNegative)
candidate = std::max(candidate, lower);
if (candidate < row[to])
{
row[to] = candidate;
if constexpr (RestorePath)
path[to] = following;
}
}
}
}
}
#endif
template <bool RestorePath, bool HasNegative, bool FiniteRange = false, bool Dense = false, class Distance, auto UseSimd = false, bool CustomInf = false>
inline bool FloydWarshallRun(std::vector<std::vector<Distance>> &distance,
Distance unreachable, Distance lower,
std::vector<std::vector<int>> *next, std::int64_t requested_inf = kInf)
{
const std::int64_t inf = CustomInf ? requested_inf : kInf;
const std::size_t n = distance.size();
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
if constexpr (static_cast<bool>(UseSimd) && std::is_same_v<Distance, std::int64_t>)
FloydWarshallRelaxAvx2<RestorePath, HasNegative,
#if !defined(__clang__)
FiniteRange && std::is_same_v<decltype(UseSimd), FloydWarshallSimdMode>,
#endif
Dense || (FiniteRange && std::is_same_v<decltype(UseSimd), FloydWarshallSimdMode>)>(distance, unreachable, lower, next);
else
#endif
{
for (std::size_t via = 0; via < n; ++via)
{
const auto *through = distance[via].data();
for (std::size_t from = 0; from < n; ++from)
{
auto *row = distance[from].data();
const Distance prefix = row[via];
if (prefix == unreachable)
continue;
for (std::size_t to = 0; to < n; ++to)
{
if constexpr (!Dense) if (through[to] == unreachable)
continue;
Distance candidate = prefix + through[to];
if constexpr (HasNegative)
candidate = std::max(candidate, lower);
if constexpr (RestorePath)
{
if (candidate < row[to])
{
row[to] = candidate;
(*next)[from][to] = (*next)[from][via];
}
}
else
row[to] = std::min(row[to], candidate);
}
}
}
}
if constexpr (FiniteRange) return false;
std::vector<std::size_t> negative;
for (std::size_t vertex = 0; vertex < n; ++vertex)
if (distance[vertex][vertex] < Distance{0})
negative.push_back(vertex);
const Distance affected = lower + Distance{-1};
for (const std::size_t via : negative)
{
// 同じ強連結成分の負閉路は一度の伝播で足りる。
if (distance[via][via] == affected)
continue;
for (std::size_t from = 0; from < n; ++from)
{
if (distance[from][via] == unreachable)
continue;
for (std::size_t to = 0; to < n; ++to)
if (!(distance[via][to] == unreachable))
{
distance[from][to] = affected;
if constexpr (RestorePath)
(*next)[from][to] = -1;
}
}
}
for (auto &row : distance)
for (auto &value : row)
{
if (value == unreachable)
value = Distance{inf};
else if (value == affected)
value = Distance{-inf};
else if (!(Distance{-inf} < value) || !(value < Distance{inf}))
throw std::overflow_error("FloydWarshall: finite distance collides with INF/-INF");
}
return !negative.empty();
}
inline void CheckFloydVertexCount(std::size_t vertices) {
if (vertices > static_cast<std::size_t>(std::numeric_limits<int>::max()))
throw std::length_error("FloydWarshall: too many vertices");
}
template <bool RestorePath, auto UseSimd = false, bool CustomInf = false>
inline bool FloydWarshallImpl(std::vector<std::vector<std::int64_t>> &distance,
std::vector<std::vector<int>> *next, std::int64_t requested_inf = kInf)
{
const std::int64_t inf = CustomInf ? requested_inf : kInf;
const std::size_t n = distance.size();
CheckFloydVertexCount(n);
if constexpr (RestorePath)
next->assign(n, std::vector<int>(n, -1));
if (n == 0)
return false;
if (n == 1)
{
#ifndef SKIP_RUNTIME_CHECKS
if (distance[0].size() != 1)
throw std::invalid_argument("FloydWarshall: matrix must be square");
if (distance[0][0] != inf && (distance[0][0] <= -inf || distance[0][0] >= inf))
throw std::out_of_range("FloydWarshall: weight must be in (-INF, INF)");
#endif
const bool negative = distance[0][0] < 0;
distance[0][0] = negative ? -inf : 0;
if constexpr (RestorePath)
(*next)[0][0] = negative ? -1 : 0;
return negative;
}
std::int64_t maximum = 0;
bool has_negative = false;
bool dense = true;
constexpr auto unreachable = std::numeric_limits<std::int64_t>::max();
for (std::size_t from = 0; from < n; ++from)
{
auto &row = distance[from];
#ifndef SKIP_RUNTIME_CHECKS
if (row.size() != n)
throw std::invalid_argument("FloydWarshall: matrix must be square");
#endif
for (std::size_t to = 0; to < n; ++to)
{
auto &value = row[to];
#ifndef SKIP_RUNTIME_CHECKS
if (value != inf && (value <= -inf || value >= inf))
throw std::out_of_range("FloydWarshall: weight must be in (-INF, INF)");
#endif
if (from == to)
value = std::min(value, std::int64_t{0});
if (value == inf) {
dense = false;
continue;
}
maximum = std::max(maximum, value < 0 ? -value : value);
has_negative = has_negative || value < 0;
if constexpr (RestorePath)
(*next)[from][to] = static_cast<int>(to);
}
}
// 非負で最長単純路もinf未満なら、未接続値と出力の変換が要らない。
if (!has_negative && maximum <= (inf - 1) / static_cast<std::int64_t>(n) &&
(!CustomInf || maximum <= unreachable / (2 * static_cast<std::int64_t>(n)))) {
if (dense) return FloydWarshallRun<RestorePath, false, true, true, std::int64_t, UseSimd, CustomInf>(distance, inf, std::int64_t{0}, next, inf);
return FloydWarshallRun<RestorePath, false, true, false, std::int64_t, UseSimd, CustomInf>(distance, inf, std::int64_t{0}, next, inf);
}
for (auto& row : distance)
for (auto& value : row)
if (value == inf) value = unreachable;
// 単純路はn-1辺以下。下限は-n*maximumで、負閉路での際限ない減少を抑える。
if (maximum <= unreachable / (2 * static_cast<std::int64_t>(n)))
{
const auto lower = -static_cast<std::int64_t>(n) * maximum;
if (has_negative)
return FloydWarshallRun<RestorePath, true, false, false, std::int64_t, UseSimd, CustomInf>(distance, unreachable, lower, next, inf);
return FloydWarshallRun<RestorePath, false, false, false, std::int64_t, UseSimd, CustomInf>(distance, unreachable, lower, next, inf);
}
using Wide = FloydWarshallWide;
const Wide wide_unreachable = (CustomInf ? FloydWarshallCustomLimit(n, inf) : FloydWarshallLimit(n)) + Wide{1};
std::vector<std::vector<Wide>> wide(n, std::vector<Wide>(n));
for (std::size_t from = 0; from < n; ++from)
for (std::size_t to = 0; to < n; ++to)
wide[from][to] = distance[from][to] == unreachable ? wide_unreachable : Wide{distance[from][to]};
const bool negative = has_negative
? FloydWarshallRun<RestorePath, true, false, false, Wide, false, CustomInf>(wide, wide_unreachable, -(CustomInf ? FloydWarshallCustomLimit(n, inf) : FloydWarshallLimit(n)), next, inf)
: FloydWarshallRun<RestorePath, false, false, false, Wide, false, CustomInf>(wide, wide_unreachable, -(CustomInf ? FloydWarshallCustomLimit(n, inf) : FloydWarshallLimit(n)), next, inf);
for (std::size_t from = 0; from < n; ++from)
for (std::size_t to = 0; to < n; ++to)
distance[from][to] = static_cast<std::int64_t>(wide[from][to]);
return negative;
}
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
#if !defined(__clang__)
template <bool RestorePath>
[[gnu::noinline]] inline bool FloydWarshallFiniteVectorized(
std::vector<std::vector<std::int64_t>> &distance, std::vector<std::vector<int>> *next)
{
return FloydWarshallImpl<RestorePath, FloydWarshallSimdMode::Finite>(distance, next);
}
#endif
template <bool RestorePath>
[[gnu::noinline]] inline bool FloydWarshallVectorized(
std::vector<std::vector<std::int64_t>> &distance, std::vector<std::vector<int>> *next)
{
#if !defined(__clang__)
if (distance.size() >= 64)
return FloydWarshallFiniteVectorized<RestorePath>(distance, next);
#endif
return FloydWarshallImpl<RestorePath, true>(distance, next);
}
#endif
} // namespace reinsirk::detail
inline bool FloydWarshall(std::vector<std::vector<std::int64_t>> &distances,
std::int64_t inf = (std::int64_t{1} << 60))
{
if (inf <= 0) throw std::invalid_argument("FloydWarshall: inf must be positive");
if (inf != kInf) return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::FloydWarshallImpl<false, false, true>(distances, nullptr, inf);
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) && !(defined(__clang__) && defined(__AVX2__))
#if defined(__clang__)
constexpr std::size_t threshold = 32;
#else
constexpr std::size_t threshold = 8;
#endif
if (distances.size() >= threshold && __builtin_cpu_supports("avx2")) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::FloydWarshallVectorized<false>(distances, nullptr);
}
#endif
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::FloydWarshallImpl<false>(distances, nullptr);
}
inline bool FloydWarshall(std::vector<std::vector<std::int64_t>> &distances,
std::vector<std::vector<int>> &next,
std::int64_t inf = (std::int64_t{1} << 60))
{
if (inf <= 0) throw std::invalid_argument("FloydWarshall: inf must be positive");
if (inf != kInf) return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::FloydWarshallImpl<true, false, true>(distances, &next, inf);
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
#if defined(__clang__)
constexpr std::size_t threshold = 16;
#else
constexpr std::size_t threshold = 8;
#endif
if (distances.size() >= threshold && __builtin_cpu_supports("avx2")) {
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::FloydWarshallVectorized<true>(distances, &next);
}
#endif
return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::FloydWarshallImpl<true>(distances, &next);
}
inline std::vector<int> FloydWarshallPath(const std::vector<std::vector<int>> &next,
int from, int to)
{
const std::size_t n = next.size();
#ifndef SKIP_RUNTIME_CHECKS
if (from < 0 || to < 0 || static_cast<std::size_t>(from) >= n || static_cast<std::size_t>(to) >= n)
throw std::out_of_range("FloydWarshallPath: invalid vertex");
#endif
std::vector<int> path;
const auto target = static_cast<std::size_t>(to);
for (std::size_t steps = 0; steps <= n; ++steps)
{
const auto current = static_cast<std::size_t>(from);
#ifndef SKIP_RUNTIME_CHECKS
if (next[current].size() != n)
throw std::invalid_argument("FloydWarshallPath: table must be square");
#endif
const int following = next[current][target];
if (following == -1)
return {};
path.push_back(from);
if (from == to)
return path;
#ifndef SKIP_RUNTIME_CHECKS
if (following < 0 || static_cast<std::size_t>(following) >= n)
throw std::out_of_range("FloydWarshallPath: invalid next vertex");
#endif
from = following;
}
throw std::invalid_argument("FloydWarshallPath: cyclic next table");
}
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1