競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
無向グラフから、選んだ頂点同士が隣接しないようにできるだけ多くの頂点を選びます。重み版では頂点の重みの合計を最大化します。
const std::array edges{std::pair{0, 1}, std::pair{1, 2}};
const auto vertices = sirkit::maximum_independent_set(3, edges); // {0, 2}
const std::array<std::int64_t, 3> weights{2, 5, 2};
const auto result = sirkit::maximum_weight_independent_set(weights, edges);
// result.weight == 5, result.vertices == {1}
maximum_independent_setstd::vector<int> maximum_independent_set(int n, std::span<const std::pair<int, int>> edges);
最大個数の独立集合を、頂点番号の昇順で返します。頂点数は0〜46、端点の番号は [0,n) です。多重辺を扱え、自己辺のある頂点は選びません。頂点数 $n$、辺数 $m$ に対して $O(n+m+2^{\lceil n/2\rceil})$ 時間、$O(n+2^{\lfloor n/2\rfloor})$ 領域です。
maximum_weight_independent_setMaximumWeightIndependentSetResult maximum_weight_independent_set(
std::span<const std::int64_t> weights, std::span<const std::pair<int, int>> edges);
weights の長さを頂点数とし、weight に最大の合計、vertices に選んだ頂点を昇順で返します。重みが0以下の頂点は選びません。最適値が std::int64_t を超えると std::overflow_error を送出します。グラフの条件と計算量は maximum_independent_set と共通です。
maximum_independent_set(n,edges): 最大個数の独立集合を、頂点番号の昇順で返す。
maximum_weight_independent_set(weights,edges): 最大重みの独立集合を{weight,vertices}で返す。
重み版は非正の頂点を含めない。最適値がint64_tの上限を超えるとoverflow_error。
どちらも頂点数は0以上46以下。重複辺は可、自己辺のある頂点は選ばない。
半分全列挙によりO(n+m+2^ceil(n/2))時間・O(n+2^floor(n/2))領域。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| Maximum Independent Set | maximum_independent_set.cpp | ✓ 現行AC | AC |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 未測定 |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/maximum_independent_set.md
//
// API一覧
// maximum_independent_set(n,edges): 最大個数の独立集合を、頂点番号の昇順で返す。
// maximum_weight_independent_set(weights,edges): 最大重みの独立集合を{weight,vertices}で返す。
// 重み版は非正の頂点を含めない。最適値がint64_tの上限を超えるとoverflow_error。
// どちらも頂点数は0以上46以下。重複辺は可、自己辺のある頂点は選ばない。
// 半分全列挙によりO(n+m+2^ceil(n/2))時間・O(n+2^floor(n/2))領域。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <span>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_MAXIMUM_INDEPENDENT_SET_DEFINED
#define SIRKIT_MAXIMUM_INDEPENDENT_SET_DEFINED
inline constexpr int kMaxIndependentSetVertices = 46;
struct MaximumWeightIndependentSetResult
{
std::int64_t weight;
std::vector<int> vertices;
};
namespace detail
{
using IndependentSetMask = std::uint64_t;
inline constexpr auto kIndependentSetOverflow = std::uint64_t{1} << 63;
struct IndependentSetGraph
{
std::array<IndependentSetMask, kMaxIndependentSetVertices> neighbors{};
IndependentSetMask eligible = 0;
};
inline IndependentSetGraph make_independent_set_graph(int n, std::span<const std::pair<int, int>> edges)
{
if (n < 0 || n > kMaxIndependentSetVertices)
{
throw std::length_error("maximum_independent_set: vertex count must be in [0,46]");
}
IndependentSetGraph graph;
graph.eligible = (IndependentSetMask{1} << n) - 1;
for (const auto &[u, v] : edges)
{
#ifndef SKIP_RUNTIME_CHECKS
if (u < 0 || u >= n || v < 0 || v >= n)
{
throw std::out_of_range("maximum_independent_set: vertex out of range");
}
#endif
const auto from = IndependentSetMask{1} << u;
const auto to = IndependentSetMask{1} << v;
graph.neighbors[u] |= to;
graph.neighbors[v] |= from;
if (u == v)
{
graph.eligible &= ~from;
}
}
return graph;
}
template <class Score>
Score add_independent_set_scores(Score a, Score b)
{
if constexpr (std::is_same_v<Score, std::uint64_t>)
{
return a <= kIndependentSetOverflow - b ? a + b : kIndependentSetOverflow;
}
else
{
return static_cast<Score>(a + b);
}
}
template <class Score>
MaximumWeightIndependentSetResult solve_independent_set(
const IndependentSetGraph &graph, const std::array<Score, kMaxIndependentSetVertices> &weights)
{
std::array<int, kMaxIndependentSetVertices> vertices{};
std::array<int, kMaxIndependentSetVertices> indices{};
IndependentSetMask selected = 0;
Score base = 0;
int count = 0;
for (auto remaining = graph.eligible; remaining != 0; remaining &= remaining - 1)
{
const int v = std::countr_zero(remaining);
if ((graph.neighbors[v] & graph.eligible) == 0)
{
// 候補同士で隣接しない正の重みの頂点は必ず採用できる。
selected |= IndependentSetMask{1} << v;
base = add_independent_set_scores(base, weights[v]);
}
else
{
indices[v] = count;
vertices[count++] = v;
}
}
std::array<IndependentSetMask, kMaxIndependentSetVertices> neighbors{};
for (int i = 0; i < count; ++i)
{
for (auto rest = graph.neighbors[vertices[i]] & graph.eligible; rest != 0; rest &= rest - 1)
{
neighbors[i] |= IndependentSetMask{1} << indices[std::countr_zero(rest)];
}
}
using HalfMask = std::uint32_t;
const int right_count = count / 2;
const int left_count = count - right_count;
const auto left_full = (HalfMask{1} << left_count) - 1;
const auto right_full = (HalfMask{1} << right_count) - 1;
std::array<HalfMask, kMaxIndependentSetVertices> left_neighbors{};
std::array<HalfMask, kMaxIndependentSetVertices> right_neighbors{};
for (int i = 0; i < count; ++i)
{
left_neighbors[i] = static_cast<HalfMask>(neighbors[i]) & left_full;
right_neighbors[i] = static_cast<HalfMask>(neighbors[i] >> left_count);
}
// best_right[mask]は右側でmaskに含まれる頂点だけ使った場合の最適値。
std::vector<Score> best_right(static_cast<std::size_t>(right_full) + 1);
for (HalfMask mask = 1; mask <= right_full; ++mask)
{
const int v = left_count + std::countr_zero(mask);
const auto without = mask & (mask - 1);
const auto take = add_independent_set_scores(weights[vertices[v]], best_right[without & ~right_neighbors[v]]);
best_right[mask] = std::max(best_right[without], take);
}
Score best = 0;
HalfMask best_left = 0;
HalfMask allowed_right = 0;
const auto enumerate = [&](auto &&self, HalfMask candidates, HalfMask right, Score score, HalfMask subset) -> void
{
const auto total = add_independent_set_scores(score, best_right[right]);
if (total > best)
{
best = total;
best_left = subset;
allowed_right = right;
}
while (candidates != 0)
{
const int u = std::countr_zero(candidates);
const auto bit = HalfMask{1} << u;
candidates ^= bit;
const auto next_score = add_independent_set_scores(score, weights[vertices[u]]);
self(self, candidates & ~left_neighbors[u], right & ~right_neighbors[u], next_score, subset | bit);
}
};
enumerate(enumerate, left_full, right_full, base, 0);
if constexpr (std::is_same_v<Score, std::uint64_t>)
{
if (best == kIndependentSetOverflow)
{
throw std::overflow_error("maximum_weight_independent_set: total weight does not fit int64_t");
}
}
while (best_left != 0)
{
selected |= IndependentSetMask{1} << vertices[std::countr_zero(best_left)];
best_left &= best_left - 1;
}
while (allowed_right != 0)
{
const int v = left_count + std::countr_zero(allowed_right);
const auto without = allowed_right & (allowed_right - 1);
if (best_right[allowed_right] != best_right[without])
{
selected |= IndependentSetMask{1} << vertices[v];
allowed_right = without & ~right_neighbors[v];
}
else
{
allowed_right = without;
}
}
MaximumWeightIndependentSetResult result{static_cast<std::int64_t>(best), {}};
for (; selected != 0; selected &= selected - 1)
{
result.vertices.push_back(std::countr_zero(selected));
}
return result;
}
} // namespace detail
inline std::vector<int> maximum_independent_set(int n, std::span<const std::pair<int, int>> edges)
{
const auto graph = detail::make_independent_set_graph(n, edges);
std::array<std::uint8_t, kMaxIndependentSetVertices> weights;
weights.fill(1);
return detail::solve_independent_set(graph, weights).vertices;
}
inline MaximumWeightIndependentSetResult maximum_weight_independent_set(
std::span<const std::int64_t> weights, std::span<const std::pair<int, int>> edges)
{
if (weights.size() > kMaxIndependentSetVertices)
{
throw std::length_error("maximum_weight_independent_set: vertex count must be in [0,46]");
}
auto graph = detail::make_independent_set_graph(static_cast<int>(weights.size()), edges);
std::array<std::uint64_t, kMaxIndependentSetVertices> positive_weights{};
for (std::size_t v = 0; v < weights.size(); ++v)
{
if (weights[v] <= 0)
{
graph.eligible &= ~(detail::IndependentSetMask{1} << v);
}
else
{
positive_weights[v] = static_cast<std::uint64_t>(weights[v]);
}
}
return detail::solve_independent_set(graph, positive_weights);
}
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1