競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
各頂点の上限を守って木の辺を選び、選んだ辺の重みの総和を最大にします。上限をすべて1にすると、木の最大重みマッチングになります。
const std::array cap{1, 1, 1};
const std::array edges{sirkit::TreeBMatchingEdge{0, 1, 4},
sirkit::TreeBMatchingEdge{1, 2, 7}};
const auto best = sirkit::maximum_weight_tree_b_matching(cap, edges);
// best.weight == 7、best.edge_ids == {1}。
maximum_weight_tree_b_matchingTreeBMatchingResult maximum_weight_tree_b_matching(
std::span<const int> max_degree, std::span<const TreeBMatchingEdge> edges);
頂点番号は0始まりです。max_degree[v] に非負の次数上限、TreeBMatchingEdge{from, to, weight} に無向辺と符号付き64ビットの重みを渡します。
weight は最大の重みの和、edge_ids は選んだ辺の0始まりの入力添字です。複数の最適解があればそのうち1つを返し、辺を選ばない解も認めます。空木と1頂点は重み0・辺列は空。最適値が std::int64_t の範囲外なら std::overflow_error を送出します。
頂点数を $n$ として $O(1+n\log(n+1))$ 時間・$O(1+n)$ 領域です。
使用例 / Verify / AtCoderの解説
maximum_weight_tree_b_matching(max_degree,edges): 各頂点の選択次数をmax_degree以下にして、辺重みの和を最大化。
TreeBMatchingEdge{from,to,weight}: 頂点は0始まり、辺の重みは符号付き64ビット。
TreeBMatchingResult{weight,edge_ids}: 最大値と、選んだ辺の入力添字。辺を選ばない解も許す。
非負の次数上限と無向木を渡す。空木・1頂点では重み0と空の辺列。最適値のint64_t超過はoverflow_error。
深い木でも非再帰。O(1+n log(n+1))時間・O(1+n)領域。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| F - Select Edges | tree_b_matching.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// 参考(親辺を残す木DP): https://atcoder.jp/contests/abc259/editorial/4296
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/tree_b_matching.md
//
// API一覧
// maximum_weight_tree_b_matching(max_degree,edges): 各頂点の選択次数をmax_degree以下にして、辺重みの和を最大化。
// TreeBMatchingEdge{from,to,weight}: 頂点は0始まり、辺の重みは符号付き64ビット。
// TreeBMatchingResult{weight,edge_ids}: 最大値と、選んだ辺の入力添字。辺を選ばない解も許す。
// 非負の次数上限と無向木を渡す。空木・1頂点では重み0と空の辺列。最適値のint64_t超過はoverflow_error。
// 深い木でも非再帰。O(1+n log(n+1))時間・O(1+n)領域。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <stdexcept>
#include <utility>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_TREE_B_MATCHING_DEFINED
#define SIRKIT_TREE_B_MATCHING_DEFINED
struct TreeBMatchingEdge
{
int from;
int to;
std::int64_t weight;
};
struct TreeBMatchingResult
{
std::int64_t weight;
std::vector<std::size_t> edge_ids;
};
namespace detail
{
struct TreeBMatchingArc
{
int child;
std::size_t edge;
};
struct TreeBMatchingGain
{
std::int64_t value;
TreeBMatchingArc arc;
};
using TreeBMatchingGraph = std::vector<std::vector<TreeBMatchingArc>>;
inline TreeBMatchingGraph tree_b_matching_graph(std::span<const int> max_degree,
std::span<const TreeBMatchingEdge> edges)
{
TreeBMatchingGraph graph(max_degree.size());
#ifndef SKIP_RUNTIME_CHECKS
for (const int cap : max_degree)
{
if (cap < 0)
{
throw std::invalid_argument("maximum_weight_tree_b_matching: negative degree limit");
}
}
#endif
for (std::size_t id = 0; id < edges.size(); ++id)
{
const auto &[from, to, weight] = edges[id];
#ifndef SKIP_RUNTIME_CHECKS
if (from < 0 || static_cast<std::size_t>(from) >= graph.size() ||
to < 0 || static_cast<std::size_t>(to) >= graph.size())
{
throw std::out_of_range("maximum_weight_tree_b_matching: vertex out of range");
}
#endif
graph[from].push_back({to, id});
graph[to].push_back({from, id});
}
return graph;
}
inline std::vector<int> tree_b_matching_order(const TreeBMatchingGraph &graph, std::span<int> parent)
{
std::vector<int> order{0};
parent[0] = -1;
order.reserve(graph.size());
for (std::size_t i = 0; i < order.size(); ++i)
{
const int v = order[i];
for (const auto &[to, id] : graph[v])
{
if (parent[to] == -2)
{
parent[to] = v;
order.push_back(to);
}
}
}
#ifndef SKIP_RUNTIME_CHECKS
if (order.size() != graph.size())
{
throw std::invalid_argument("maximum_weight_tree_b_matching: graph is not a tree");
}
#endif
return order;
}
} // namespace detail
inline TreeBMatchingResult maximum_weight_tree_b_matching(
std::span<const int> max_degree, std::span<const TreeBMatchingEdge> edges)
{
const auto n = max_degree.size();
if (edges.size() != n - static_cast<std::size_t>(n != 0))
{
throw std::invalid_argument("maximum_weight_tree_b_matching: incorrect number of edges");
}
if (n == 0)
{
return {0, {}};
}
const auto graph = detail::tree_b_matching_graph(max_degree, edges);
std::vector<int> parent(n, -2);
const auto order = detail::tree_b_matching_order(graph, parent);
std::vector<std::int64_t> penalty(n);
std::vector<detail::TreeBMatchingGain> gains;
std::vector<detail::TreeBMatchingArc> retained;
retained.reserve(edges.size());
std::vector<std::pair<std::size_t, std::size_t>> choice(n);
TreeBMatchingResult result{0, {}};
for (auto it = order.rbegin(); it != order.rend(); ++it)
{
const int v = *it;
if (max_degree[v] == 0)
{
continue;
}
gains.clear();
for (const auto &arc : graph[v])
{
const int u = arc.child;
if (parent[u] != v || max_degree[u] == 0)
{
continue;
}
// 親辺に枠を使うとき、子側で諦める利得は子の最後の採用分だけ。
const auto weight = edges[arc.edge].weight;
if (weight > penalty[u])
{
gains.push_back({weight - penalty[u], arc});
}
}
std::sort(gains.begin(), gains.end(), [](const auto &a, const auto &b)
{
if (a.value != b.value)
{
return a.value > b.value;
}
return a.arc.edge < b.arc.edge;
});
const auto limit = static_cast<std::size_t>(max_degree[v]);
const auto take = std::min(limit, gains.size());
choice[v] = {retained.size(), take};
if (take == limit)
{
penalty[v] = gains[take - 1].value;
}
for (std::size_t i = 0; i < take; ++i)
{
// 全頂点の採用利得の和は、根の木DPと等しい。後続の利得も非負。
if (gains[i].value > std::numeric_limits<std::int64_t>::max() - result.weight)
{
throw std::overflow_error("maximum_weight_tree_b_matching: optimal weight does not fit int64_t");
}
result.weight += gains[i].value;
retained.push_back(gains[i].arc);
}
}
std::vector<bool> parent_selected(n);
result.edge_ids.reserve(retained.size());
for (const int v : order)
{
const auto [first, take] = choice[v];
const auto loss = parent_selected[v] && take == static_cast<std::size_t>(max_degree[v]);
for (std::size_t i = 0; i < take - static_cast<std::size_t>(loss); ++i)
{
const auto [u, id] = retained[first + i];
parent_selected[u] = true;
result.edge_ids.push_back(id);
}
}
return result;
}
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1