競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
非負の重み付き無向木で、距離が最も長いパスとその長さを求めます。
const std::vector<sirkit::TreeDiameterEdge> edges{{0, 1, 4}, {1, 2, 3}, {1, 3, 8}};
const auto result = sirkit::tree_diameter(4, edges);
// result.length == 12。result.path は {0, 1, 3} またはその逆順。
tree_diameterTreeDiameterResult tree_diameter(int n, std::span<const TreeDiameterEdge> edges);
TreeDiameterEdge{from, to, weight} は0始まりの端点を持つ無向辺です。各辺を1回ずつ渡します。重みは非負の std::int64_t です。
戻り値の length は直径の長さ、path は経路上の頂点列です。頂点が0個なら長さ0と空の列を、1個の場合や全辺の重みが0の場合は長さ0と {0} を返します。直径の長さが std::int64_t の範囲を超えたときの例外は std::overflow_error です。
頂点数を n として、時間と追加領域は O(n) です。走査と経路の復元は反復で行います。
使用例 / Verify / Luzhiledの解説
TreeDiameterEdge {from,to,weight}: 0始まりの端点と非負のstd::int64_t重みを持つ無向辺。
TreeDiameterResult {length,path}: 直径の長さと、直径をなすパスの頂点列。
tree_diameter(n,edges): n頂点の無向木の直径とパスを返す。O(n)時間・領域。
n=0では{0,{}}、n=1や全辺の重みが0なら{0,{0}}。同じ長さのパスが複数あれば1つを返す。
長さがstd::int64_tの範囲を超えるとstd::overflow_error。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Tree Diameter | tree_diameter.cpp | ✓ 現行AC | AC |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 未測定 |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// 参考(2回の木の走査): https://ei1333.github.io/luzhiled/snippets/tree/tree-diameter.html
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/tree_diameter.md
//
// API一覧
// TreeDiameterEdge {from,to,weight}: 0始まりの端点と非負のstd::int64_t重みを持つ無向辺。
// TreeDiameterResult {length,path}: 直径の長さと、直径をなすパスの頂点列。
// tree_diameter(n,edges): n頂点の無向木の直径とパスを返す。O(n)時間・領域。
// n=0では{0,{}}、n=1や全辺の重みが0なら{0,{0}}。同じ長さのパスが複数あれば1つを返す。
// 長さがstd::int64_tの範囲を超えるとstd::overflow_error。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <cstddef>
#include <cstdint>
#include <limits>
#include <numeric>
#include <span>
#include <stdexcept>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_TREE_DIAMETER_DEFINED
#define SIRKIT_TREE_DIAMETER_DEFINED
struct TreeDiameterEdge
{
int from;
int to;
std::int64_t weight;
};
struct TreeDiameterResult
{
std::int64_t length;
std::vector<int> path;
};
inline TreeDiameterResult tree_diameter(int n, std::span<const TreeDiameterEdge> edges)
{
#ifndef SKIP_RUNTIME_CHECKS
if (n < 0)
{
throw std::invalid_argument("tree_diameter: negative vertex count");
}
#endif
const auto vertices = static_cast<std::size_t>(n);
#ifndef SKIP_RUNTIME_CHECKS
if (edges.size() != (vertices == 0 ? 0 : vertices - 1))
{
throw std::invalid_argument("tree_diameter: wrong edge count");
}
#endif
if (vertices == 0)
{
return {0, {}};
}
if (vertices == 1)
{
return {0, {0}};
}
std::vector<std::size_t> offset(vertices + 1);
for (const auto &[from, to, weight] : edges)
{
#ifndef SKIP_RUNTIME_CHECKS
if (static_cast<std::size_t>(from) >= vertices || static_cast<std::size_t>(to) >= vertices)
{
throw std::out_of_range("tree_diameter: invalid endpoint");
}
if (from == to || weight < 0)
{
throw std::invalid_argument("tree_diameter: loop or negative weight");
}
#endif
++offset[from];
++offset[to];
}
std::partial_sum(offset.begin(), offset.end(), offset.begin());
struct Arc
{
int to;
std::int64_t weight;
};
std::vector<Arc> arcs(2 * edges.size());
// 各頂点の区間を後ろから埋めると、offsetをそのまま区間の先頭に使える。
for (const auto &[from, to, weight] : edges)
{
arcs[--offset[from]] = {to, weight};
arcs[--offset[to]] = {from, weight};
}
std::vector<int> parent(vertices, -1);
std::vector<std::int64_t> distance(vertices);
std::vector<int> order;
order.reserve(vertices);
const auto farthest_from = [&](int root, [[maybe_unused]] bool check_tree)
{
int farthest = root;
order.clear();
order.push_back(root);
parent[root] = root;
distance[root] = 0;
for (std::size_t i = 0; i < order.size(); ++i)
{
const int from = order[i];
for (std::size_t j = offset[from]; j < offset[from + 1]; ++j)
{
const auto &[to, weight] = arcs[j];
if (to == parent[from])
{
continue;
}
#ifndef SKIP_RUNTIME_CHECKS
if (check_tree && parent[to] != -1)
{
throw std::invalid_argument("tree_diameter: cycle");
}
#endif
if (weight > std::numeric_limits<std::int64_t>::max() - distance[from])
{
throw std::overflow_error("tree_diameter: path length overflow");
}
parent[to] = from;
distance[to] = distance[from] + weight;
if (distance[to] > distance[farthest])
{
farthest = to;
}
order.push_back(to);
}
}
return farthest;
};
const int start = farthest_from(0, true);
#ifndef SKIP_RUNTIME_CHECKS
if (order.size() != vertices)
{
throw std::invalid_argument("tree_diameter: disconnected");
}
#endif
const int end = farthest_from(start, false);
TreeDiameterResult result{distance[end], {}};
for (int vertex = end; vertex != start; vertex = parent[vertex])
{
result.path.push_back(vertex);
}
result.path.push_back(start);
return result;
}
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1