競技プログラミング用 C++ ライブラリ
graph/offline_dynamic_connectivity.hpp · GitHub で見る
共通ページ
無向グラフの辺の追加・削除と問い合わせを登録し、最後にまとめて計算します。Rollback Union Find を利用します。
#include "lib/graph/offline_dynamic_connectivity.hpp"
#include <cassert>
int main() {
OfflineDynamicConnectivity graph(4);
graph.link(0, 1);
int a = graph.query_same(0, 1);
graph.link(1, 2);
int b = graph.query_size(0);
graph.cut(1, 0);
int c = graph.query_same(0, 2);
int d = graph.query_component_count();
auto answer = graph.solve();
assert(answer[a] == 1 && answer[b] == 3);
assert(answer[c] == 0 && answer[d] == 3);
}
頂点は [0,n) です。各 query_* の返り値は0始まりの問い合わせ ID で、solve() の配列をその ID で参照します。問い合わせは登録した位置での状態を調べます。辺の更新だけでは問い合わせ ID は増えません。
| 操作 | 内容・返り値 | 計算量 |
|---|---|---|
OfflineDynamicConnectivity(n=0) |
頂点数だけを登録。初期状態では辺なし | \(O(1)\) |
reset(n) |
頂点数を変え、全ての更新・問い合わせを削除 | \(O(M+T)\) |
reserve(updates,queries=0) |
辺の更新回数・問い合わせ回数を目安に領域を確保 | \(O(M+T)\) |
vertex_count() / query_count()
|
頂点数/登録した問い合わせ数 | \(O(1)\) |
link(u,v) |
無向辺を1本追加する操作を登録 | 償却 \(O(1)\) |
cut(u,v) |
無向辺を1本削除する操作を登録。存在しなければ何もしない | 償却 \(O(1)\) |
query_same(u,v) |
連結判定を登録し、問い合わせ ID を返す。答えは0または1 | 償却 \(O(1)\) |
query_size(v) |
v の成分サイズの問い合わせを登録 |
償却 \(O(1)\) |
query_component_count() |
成分数の問い合わせを登録 | 償却 \(O(1)\) |
solve() |
登録した問い合わせの答えを vector<int> で返す |
\(O(n+M+(T+K)\log n)\) |
query() |
任意の問い合わせ位置だけを登録し、問い合わせ ID を返す | 償却 \(O(1)\) |
run(visit) |
全問い合わせを visit(id,const_uf) で処理 |
\(O(n+M+T+K\log n)\) |
run(on_link,on_cut,visit) |
成功した併合・その取り消しの通知を受けながら問い合わせを処理 | \(O(n+M+T+K\log n)\) |
並行辺に対応します。同じ辺を2本追加すると、1本削除した後も連結関係に使われます。link(0,1) と link(1,0) は同じ辺として扱います。自己ループは連結性を変えないため、登録時に無視します。
solve・run は登録内容を変更しません。繰り返し計算でき、登録を追加してから再計算することもできます。その場合は以前の問い合わせも含めて全体を計算し直します。頂点数0でも query_component_count と query() は使えます。
複数の情報をまとめて調べたい場合は query() と run を使います。各問い合わせ位置の Rollback Union Find を読み取り専用で受け取れます。
OfflineDynamicConnectivity graph(3);
graph.link(0, 1);
graph.query();
graph.link(1, 2);
graph.query();
graph.run([&](int id, const RollbackUnionFind &uf) {
assert(uf.size(0) == id + 2);
});
visit は問い合わせ ID の昇順に1回ずつ呼びます。渡された uf はその呼び出しの中だけで使ってください。leader・same・size・component_count・groups を利用できます。独自の問い合わせ位置を作る query() を使った場合は、solve() ではなく run で答えを処理してください。既定の query_* も run の呼び出し対象になります。
run(on_link,on_cut,visit) の on_link(root,child) は、異なる成分を併合した直後に呼びます。新しい代表元は root、その子になった元の代表元は child です。既に連結な場合は呼びません。
on_cut(root,child) は、この併合を取り消す直前に呼びます。同じ組の on_link に対応し、取り消す順序は後入れ先出しです。これは入力の cut(u,v) の通知ではありません。内部の時間区間探索で併合を取り消すたびに呼ばれます。最後は全ての併合を取り消すため、on_link と on_cut の回数は一致します。
例えば初期頂点値の成分和を調べる場合は、外部の sum を次のように更新できます。
std::vector<long long> sum = {1, 10, 100};
OfflineDynamicConnectivity graph(3);
graph.link(0, 1);
graph.query();
graph.run([&](int root, int child) {
sum[root] += sum[child];
}, [&](int root, int child) {
sum[root] -= sum[child];
}, [&](int id, const RollbackUnionFind &uf) {
assert(id == 0 && sum[uf.leader(0)] == 11);
});
頂点値の加算も行う利用例は Dynamic Graph Vertex Add Component Sum の検証コード にあります。外部にも親を記録し、頂点への加算をその祖先まで反映することで、時刻順の加算と成分和を扱います。
独自の集計は、内部で選ばれる併合順に依存しないようにしてください。問い合わせの答えを次の辺更新の生成に使うことはできません。コールバックからこのグラフを変更しないでください。繰り返し run する場合、必要に応じて外部データも開始時の状態へ戻します。
辺の有効期間は、問い合わせがある時点だけに圧縮します。重複辺は本数が0と正の間で変わる区間にまとめ、問い合わせを含まない区間は捨てます。時間セグメント木の操作は1本の配列にまとめ、同じ成分を再度併合する処理とその履歴は省きます。ハッシュ表には依存せず、正規化した64 bitの辺キーを安定基数ソートすることで、同じ辺の登録順を保って有効期間を求めます。
頂点数を \(n\)、自己ループ以外の辺更新数を \(M\)、問い合わせ数を \(T\)、辺の有効区間数を \(I\leq M\)、時間セグメント木に置く辺 ID の総数を \(K=O(I\log T)\) とします。run は \(O(n+M+T+K\log n)\) 時間で、コールバックとその中で呼ぶ操作の計算量は別に加算します。solve は連結判定なども含めて \(O(n+M+(T+K)\log n)\) 時間です。使用中のデータは \(O(n+M+T+K)\) 空間です。保持する更新・問い合わせの数はそれぞれ INT_MAX 以下としてください。問い合わせがなければ run は何もしません。空の場合や長さ1の場合にも定数時間かかります。reset は確保済み領域を保持します。
#ifndef OFFLINE_DYNAMIC_CONNECTIVITY_HPP
#define OFFLINE_DYNAMIC_CONNECTIVITY_HPP
#include "../components/offline_time_segments.hpp"
#include "../components/radix_sort.hpp"
#include "../data_structure/rollback_union_find.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <utility>
#include <vector>
class OfflineDynamicConnectivity {
struct Event { std::uint64_t key; int time; std::uint32_t order; };
struct Query { int type, u, v; };
int n_;
std::vector<Event> events_;
std::vector<Query> queries_;
void check_([[maybe_unused]] int v) const { assert(0 <= v && v < n_); }
void update_(int u, int v, bool remove) {
check_(u), check_(v);
if (u == v) return;
assert(events_.size() < static_cast<std::size_t>(std::numeric_limits<int>::max()));
if (u > v) std::swap(u, v);
std::uint64_t key = (std::uint64_t(static_cast<unsigned>(u)) << 32) | static_cast<unsigned>(v);
std::uint32_t order = static_cast<std::uint32_t>(events_.size()) | (std::uint32_t(remove) << 31);
events_.push_back({key, query_count(), order});
}
int query_(int type, int u, int v) {
assert(queries_.size() < static_cast<std::size_t>(std::numeric_limits<int>::max()));
int id = query_count();
queries_.push_back({type, u, v});
return id;
}
template <bool Hooks, class Link, class Cut, class Visit>
void run_(Link &link, Cut &cut, Visit &visit) const {
if (queries_.empty()) return;
auto events = events_;
stable_radix_sort(events, [](const Event &event) { return event.key; });
std::vector<OfflineTimeSegments::Interval> intervals;
std::vector<std::pair<int, int>> edges;
intervals.reserve(events.size() / 2), edges.reserve(events.size() / 2);
for (std::size_t i = 0; i < events.size();) {
std::uint64_t key = events[i].key;
int count = 0, start = 0;
auto append = [&](int end) {
if (start == end) return;
intervals.push_back({start, end, static_cast<int>(edges.size())});
edges.emplace_back(static_cast<int>(key >> 32), static_cast<int>(key & 0xffffffffU));
};
do {
const auto &event = events[i++];
if (!(event.order >> 31)) {
if (count++ == 0) start = event.time;
} else if (count && --count == 0) append(event.time);
} while (i < events.size() && events[i].key == key);
if (count) append(query_count());
}
OfflineTimeSegments timeline(query_count(), intervals);
struct State {
RollbackUnionFind uf;
std::vector<std::pair<int, int>> history;
Link &link;
Cut &cut;
std::size_t snapshot() const { return uf.snapshot(); }
void merge(int u, int v) {
int a = uf.leader(u), b = uf.leader(v);
if (a == b) return;
if (uf.size(a) < uf.size(b)) std::swap(a, b);
uf.merge(a, b);
if constexpr (Hooks) {
history.emplace_back(a, b);
link(a, b);
}
}
void rollback(std::size_t saved) {
if constexpr (Hooks) {
while (uf.snapshot() > saved) {
auto [a, b] = history.back();
cut(a, b);
history.pop_back(), uf.undo();
}
} else uf.rollback(saved);
}
};
State state{RollbackUnionFind(n_), {}, link, cut};
std::size_t capacity = std::min<std::size_t>(n_ ? n_ - 1 : 0, edges.size());
state.uf.reserve(capacity);
if constexpr (Hooks) state.history.reserve(capacity);
timeline.run(state, [&](State &s, int id) { s.merge(edges[id].first, edges[id].second); },
[&](int id, const State &s) { visit(id, s.uf); });
}
public:
explicit OfflineDynamicConnectivity(int n = 0) : n_(n) { assert(n >= 0); }
void reset(int n) { assert(n >= 0); n_ = n; events_.clear(), queries_.clear(); }
void reserve(int updates, int queries = 0) {
assert(updates >= 0 && queries >= 0);
events_.reserve(updates), queries_.reserve(queries);
}
int vertex_count() const { return n_; }
int query_count() const { return static_cast<int>(queries_.size()); }
void link(int u, int v) { update_(u, v, false); }
void cut(int u, int v) { update_(u, v, true); }
int query_same(int u, int v) { check_(u), check_(v); return query_(0, u, v); }
int query_size(int v) { check_(v); return query_(1, v, 0); }
int query_component_count() { return query_(2, 0, 0); }
int query() { return query_(3, 0, 0); }
template <class Visit>
void run(Visit &&visit) const {
auto noop = [](int, int) {};
run_<false>(noop, noop, visit);
}
template <class Link, class Cut, class Visit>
void run(Link &&link, Cut &&cut, Visit &&visit) const { run_<true>(link, cut, visit); }
std::vector<int> solve() const {
std::vector<int> answers(queries_.size());
run([&](int id, const RollbackUnionFind &uf) {
const auto &q = queries_[id];
if (q.type == 0) answers[id] = uf.same(q.u, q.v);
else if (q.type == 1) answers[id] = uf.size(q.u);
else { assert(q.type == 2); answers[id] = uf.component_count(); }
});
return answers;
}
};
#endif
#line 1 "graph/offline_dynamic_connectivity.hpp"
#line 1 "components/offline_time_segments.hpp"
#include <bit>
#include <cassert>
#include <cstddef>
#include <utility>
#include <vector>
class OfflineTimeSegments {
int n_;
std::size_t base_;
std::vector<std::size_t> offset_;
std::vector<int> items_;
public:
struct Interval { int left, right, item; };
OfflineTimeSegments(int n, const std::vector<Interval> &intervals) : n_(n), base_(1) {
assert(n >= 0);
if (!n || intervals.empty()) return;
base_ = std::bit_ceil(static_cast<std::size_t>(n));
offset_.resize(base_ * 2 + 1);
auto cover = [&](const Interval &interval, auto &&visit) {
assert(0 <= interval.left && interval.left <= interval.right && interval.right <= n);
for (std::size_t l = base_ + interval.left, r = base_ + interval.right; l < r; l >>= 1, r >>= 1) {
if (l & 1) visit(l++);
if (r & 1) visit(--r);
}
};
for (const auto &interval : intervals) cover(interval, [&](std::size_t v) { ++offset_[v]; });
for (std::size_t v = 1; v < offset_.size(); ++v) offset_[v] += offset_[v - 1];
items_.resize(offset_.back());
for (const auto &interval : intervals)
cover(interval, [&](std::size_t v) { items_[--offset_[v]] = interval.item; });
}
int size() const { return n_; }
std::size_t entry_count() const { return items_.size(); }
template <class State, class Apply, class Visit>
void run(State &state, Apply &&apply, Visit &&visit) const {
if (!n_) return;
if (items_.empty()) {
for (int t = 0; t < n_; ++t) visit(t, std::as_const(state));
return;
}
auto dfs = [&](auto &&self, std::size_t v, std::size_t l, std::size_t r) -> void {
auto saved = state.snapshot();
for (std::size_t i = offset_[v]; i < offset_[v + 1]; ++i) apply(state, items_[i]);
if (r - l == 1) visit(static_cast<int>(l), std::as_const(state));
else {
std::size_t m = (l + r) / 2;
self(self, v * 2, l, m);
if (m < static_cast<std::size_t>(n_)) self(self, v * 2 + 1, m, r);
}
state.rollback(saved);
};
dfs(dfs, 1, 0, base_);
}
};
#line 1 "components/radix_sort.hpp"
#include <algorithm>
#include <array>
#line 7 "components/radix_sort.hpp"
#include <cstdint>
#include <type_traits>
#line 11 "components/radix_sort.hpp"
template <int Bits, class T, class Key>
void stable_radix_sort(std::vector<T> &values, Key &&key) {
static_assert(1 <= Bits && Bits <= 16);
constexpr unsigned buckets = 1U << Bits, mask = buckets - 1;
using K = std::remove_cvref_t<decltype(key(std::declval<const T &>()))>;
static_assert(std::is_integral_v<K> && std::is_unsigned_v<K> && sizeof(K) <= sizeof(std::uint64_t));
if (values.size() < 2) return;
if (values.size() < 256) {
std::stable_sort(values.begin(), values.end(), [&](const T &a, const T &b) { return key(a) < key(b); });
return;
}
std::uint64_t first = key(values.front()), previous = first, varying = 0;
bool sorted = true;
for (std::size_t i = 1; i < values.size(); ++i) {
std::uint64_t current = key(values[i]);
varying |= first ^ current;
sorted &= previous <= current;
previous = current;
}
if (sorted) return;
std::vector<T> scratch(values.size());
using Counts = std::conditional_t<(Bits <= 11), std::array<std::size_t, buckets>, std::vector<std::size_t>>;
Counts count = [] {
if constexpr (Bits <= 11) return Counts{};
else return Counts(buckets);
}();
for (int shift = 0; shift < 64; shift += Bits) {
if (!((varying >> shift) & mask)) continue;
std::fill(count.begin(), count.end(), 0);
for (const auto &value : values) ++count[(static_cast<std::uint64_t>(key(value)) >> shift) & mask];
std::size_t sum = 0;
for (auto &x : count) {
auto n = x;
x = sum, sum += n;
}
for (auto &&value : values) scratch[count[(static_cast<std::uint64_t>(key(value)) >> shift) & mask]++] = std::move(value);
values.swap(scratch);
}
}
template <class T, class Key>
void stable_radix_sort(std::vector<T> &values, Key key) {
stable_radix_sort<8>(values, std::move(key));
}
namespace radix_sort_detail {
template <int Bits = 8, class T, class Key>
void sort_by_key(std::vector<T> &values, Key key) {
using K = std::remove_cvref_t<decltype(key(std::declval<const T &>()))>;
if constexpr (std::is_integral_v<K> && !std::is_same_v<K, bool> && sizeof(K) <= 8 && std::is_default_constructible_v<T>) {
using U = std::make_unsigned_t<K>;
constexpr U sign = std::is_signed_v<K> ? U(1) << (sizeof(K) * 8 - 1) : U(0);
stable_radix_sort<Bits>(values, [&](const T &value) { return U(U(key(value)) ^ sign); });
} else std::sort(values.begin(), values.end(), [&](const T &a, const T &b) { return key(a) < key(b); });
}
}
#line 1 "data_structure/rollback_union_find.hpp"
#line 8 "data_structure/rollback_union_find.hpp"
class RollbackUnionFind {
struct Change { int child, size; };
std::vector<int> parent_;
std::vector<Change> history_;
int components_ = 0;
public:
explicit RollbackUnionFind(int n = 0) { reset(n); }
void reset(int n) {
assert(n >= 0);
parent_.assign(n, -1), history_.clear();
components_ = n;
}
void reserve(std::size_t updates) { history_.reserve(updates); }
int vertex_count() const { return static_cast<int>(parent_.size()); }
int component_count() const { return components_; }
int leader(int x) const {
assert(0 <= x && x < vertex_count());
while (parent_[x] >= 0) x = parent_[x];
return x;
}
bool same(int x, int y) const { return leader(x) == leader(y); }
int size(int x) const { return -parent_[leader(x)]; }
bool merge(int x, int y) {
x = leader(x), y = leader(y);
if (x == y) {
history_.push_back({-1, 0});
return false;
}
if (parent_[x] > parent_[y]) std::swap(x, y);
history_.push_back({y, parent_[y]});
parent_[x] += parent_[y], parent_[y] = x;
--components_;
return true;
}
std::size_t snapshot() const { return history_.size(); }
void undo() {
assert(!history_.empty());
auto [child, size] = history_.back();
history_.pop_back();
if (child < 0) return;
parent_[parent_[child]] -= size, parent_[child] = size;
++components_;
}
void rollback(std::size_t state = 0) {
assert(state <= history_.size());
while (history_.size() > state) undo();
}
std::vector<std::vector<int>> groups() const {
std::vector<std::vector<int>> result;
result.reserve(components_);
std::vector<int> index(vertex_count(), -1);
for (int v = 0; v < vertex_count(); ++v) {
int r = leader(v);
if (index[r] == -1) {
index[r] = static_cast<int>(result.size());
result.emplace_back();
result.back().reserve(-parent_[r]);
}
result[index[r]].push_back(v);
}
return result;
}
};
#line 11 "graph/offline_dynamic_connectivity.hpp"
#include <limits>
#line 14 "graph/offline_dynamic_connectivity.hpp"
class OfflineDynamicConnectivity {
struct Event { std::uint64_t key; int time; std::uint32_t order; };
struct Query { int type, u, v; };
int n_;
std::vector<Event> events_;
std::vector<Query> queries_;
void check_([[maybe_unused]] int v) const { assert(0 <= v && v < n_); }
void update_(int u, int v, bool remove) {
check_(u), check_(v);
if (u == v) return;
assert(events_.size() < static_cast<std::size_t>(std::numeric_limits<int>::max()));
if (u > v) std::swap(u, v);
std::uint64_t key = (std::uint64_t(static_cast<unsigned>(u)) << 32) | static_cast<unsigned>(v);
std::uint32_t order = static_cast<std::uint32_t>(events_.size()) | (std::uint32_t(remove) << 31);
events_.push_back({key, query_count(), order});
}
int query_(int type, int u, int v) {
assert(queries_.size() < static_cast<std::size_t>(std::numeric_limits<int>::max()));
int id = query_count();
queries_.push_back({type, u, v});
return id;
}
template <bool Hooks, class Link, class Cut, class Visit>
void run_(Link &link, Cut &cut, Visit &visit) const {
if (queries_.empty()) return;
auto events = events_;
stable_radix_sort(events, [](const Event &event) { return event.key; });
std::vector<OfflineTimeSegments::Interval> intervals;
std::vector<std::pair<int, int>> edges;
intervals.reserve(events.size() / 2), edges.reserve(events.size() / 2);
for (std::size_t i = 0; i < events.size();) {
std::uint64_t key = events[i].key;
int count = 0, start = 0;
auto append = [&](int end) {
if (start == end) return;
intervals.push_back({start, end, static_cast<int>(edges.size())});
edges.emplace_back(static_cast<int>(key >> 32), static_cast<int>(key & 0xffffffffU));
};
do {
const auto &event = events[i++];
if (!(event.order >> 31)) {
if (count++ == 0) start = event.time;
} else if (count && --count == 0) append(event.time);
} while (i < events.size() && events[i].key == key);
if (count) append(query_count());
}
OfflineTimeSegments timeline(query_count(), intervals);
struct State {
RollbackUnionFind uf;
std::vector<std::pair<int, int>> history;
Link &link;
Cut &cut;
std::size_t snapshot() const { return uf.snapshot(); }
void merge(int u, int v) {
int a = uf.leader(u), b = uf.leader(v);
if (a == b) return;
if (uf.size(a) < uf.size(b)) std::swap(a, b);
uf.merge(a, b);
if constexpr (Hooks) {
history.emplace_back(a, b);
link(a, b);
}
}
void rollback(std::size_t saved) {
if constexpr (Hooks) {
while (uf.snapshot() > saved) {
auto [a, b] = history.back();
cut(a, b);
history.pop_back(), uf.undo();
}
} else uf.rollback(saved);
}
};
State state{RollbackUnionFind(n_), {}, link, cut};
std::size_t capacity = std::min<std::size_t>(n_ ? n_ - 1 : 0, edges.size());
state.uf.reserve(capacity);
if constexpr (Hooks) state.history.reserve(capacity);
timeline.run(state, [&](State &s, int id) { s.merge(edges[id].first, edges[id].second); },
[&](int id, const State &s) { visit(id, s.uf); });
}
public:
explicit OfflineDynamicConnectivity(int n = 0) : n_(n) { assert(n >= 0); }
void reset(int n) { assert(n >= 0); n_ = n; events_.clear(), queries_.clear(); }
void reserve(int updates, int queries = 0) {
assert(updates >= 0 && queries >= 0);
events_.reserve(updates), queries_.reserve(queries);
}
int vertex_count() const { return n_; }
int query_count() const { return static_cast<int>(queries_.size()); }
void link(int u, int v) { update_(u, v, false); }
void cut(int u, int v) { update_(u, v, true); }
int query_same(int u, int v) { check_(u), check_(v); return query_(0, u, v); }
int query_size(int v) { check_(v); return query_(1, v, 0); }
int query_component_count() { return query_(2, 0, 0); }
int query() { return query_(3, 0, 0); }
template <class Visit>
void run(Visit &&visit) const {
auto noop = [](int, int) {};
run_<false>(noop, noop, visit);
}
template <class Link, class Cut, class Visit>
void run(Link &&link, Cut &&cut, Visit &&visit) const { run_<true>(link, cut, visit); }
std::vector<int> solve() const {
std::vector<int> answers(queries_.size());
run([&](int id, const RollbackUnionFind &uf) {
const auto &q = queries_[id];
if (q.type == 0) answers[id] = uf.same(q.u, q.v);
else if (q.type == 1) answers[id] = uf.size(q.u);
else { assert(q.type == 2); answers[id] = uf.component_count(); }
});
return answers;
}
};