sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

Link Cut Tree

DataStructure/Link_Cut_Tree.cpp · ソース · 文書 Last Commit

通常版・コンパイラ共通 · この版の一覧へ

通常版・GCC専用 · この版の一覧へ

通常版・Clang専用 · この版の一覧へ

通常版・MSVC専用 · この版の一覧へ

速度優先版・コンパイラ共通 · この版の一覧へ

速度優先版・GCC専用 · この版の一覧へ

速度優先版・Clang専用 · この版の一覧へ

速度優先版・MSVC専用 · この版の一覧へ

LinkCutTree<T,Op>は、辺を追加・削除する森で頂点の値とパスの和などを管理します。頂点番号は0始まりで、番号の大小に親子関係の意味はありません。構築直後は各頂点が孤立し、辺はlinkで追加します。基本例・非可換合成・遅延作用を参照してください。

以下、Nは要素数です。値の演算・コピーをO(1)として計算量を記します。

コンストラクタ

explicit LinkCutTree(std::span<const T> values = {}, const T& identity = T{}, Op op = Op{}, Mapping mapping = Mapping{}, Composition composition = Composition{});
explicit LinkCutTree(const std::vector<T>& values, const T& identity = T{}, Op op = Op{}, Mapping mapping = Mapping{}, Composition composition = Composition{});
LinkCutTree(const LinkCutTree& other);
LinkCutTree(LinkCutTree&& other) noexcept;

入力値を各頂点に割り当て、辺のない森を構築します。span形で引数を省略すると空の森を作ります。

制約: 冒頭の値型・演算の前提を満たすこと。指定する列長は内部容量の上限内です。

計算量: N要素にO(N+1)時間・領域。 ムーブ構築はO(1)、コピーは保持領域に比例。

bool link(int first, int last);

異なる木の2頂点を辺で結びtrueを返します。既に連結ならfalseです。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

cut

bool cut(int first, int last);

2頂点間の直接の辺を削除してtrueを返します。辺がなければfalseです。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

connected

bool connected(int first, int last);

2頂点が同じ木にあればtrueを返します。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

get

T get(int vertex);

頂点の現在値を返します。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

set

void set(int vertex, const T& value);

頂点の値をvalueへ置き換えます。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

transform

template<class Fn> void transform(int vertex, Fn&& function);

頂点の現在値へ関数を適用して置き換えます。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

path_prod

std::optional<T> path_prod(int first, int last);

first→lastの頂点値を順に集約したoptionalを返します。非連結ならnulloptです。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

path_size

std::size_t path_size(int first, int last);

経路の頂点数を返します。非連結なら0です。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

path_length

std::optional<std::size_t> path_length(int first, int last);

経路の辺数をoptionalで返します。非連結ならnulloptです。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

kth_on_path

std::optional<int> kth_on_path(int first, int last, std::size_t k);

first→lastの0始まりk番目の頂点をoptionalで返します。非連結・範囲外ならnulloptです。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

make_root

void make_root(int vertex);

指定頂点を所属する木の根にします。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

find_root

int find_root(int vertex);

所属する木の現在の根を返します。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

lca

std::optional<int> lca(int root, int first, int last);

rootを根としたときの2頂点のLCAをoptionalで返します。3頂点すべてが同じ木に属していなければnulloptです。

制約: 指定する頂点は0<=v<size()。演算中の例外後はusable()を確認すること。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

apply

void apply(int vertex, const Action& action) requires(has_action);
bool apply(int first, int last, const Action& action) requires(has_action);

頂点または経路へ作用を適用します。経路版は非連結ならfalse、適用時trueです。

制約: 作用を設定した型だけで使用可。有効な頂点番号を渡すこと。

計算量: 1回の操作は償却O(log(N+1))。演算・値のコピーをO(1)とします。

size

std::size_t size() const noexcept;

要素数を返します。

制約: 共通の型・演算条件を満たすこと。reset・clearは無効状態からの復旧にも使えます。

計算量: O(1)。

empty

bool empty() const noexcept;

空ならtrueを返します。

制約: 共通の型・演算条件を満たすこと。reset・clearは無効状態からの復旧にも使えます。

計算量: O(1)。

usable

bool usable() const noexcept;

演算中の例外によって無効化されていなければtrueを返します。

制約: 共通の型・演算条件を満たすこと。reset・clearは無効状態からの復旧にも使えます。

計算量: O(1)。

reset

void reset(std::span<const T> values);
void reset(const std::vector<T>& values);

現在の演算設定で値を取り込み、全頂点が孤立した森を作り直します。

制約: 共通の型・演算条件を満たすこと。reset・clearは無効状態からの復旧にも使えます。

計算量: O(旧N+新N+1)時間・新列の保持領域。

clear

void clear() noexcept;

空の森にして無効状態も復旧します。

制約: 共通の型・演算条件を満たすこと。reset・clearは無効状態からの復旧にも使えます。

計算量: O(旧N+1)の上界。要素・設定の破棄費用を含みます。

swap

void swap(LinkCutTree& other) noexcept;
friend void swap(LinkCutTree& first, LinkCutTree& second) noexcept;

内容と設定を交換します。

制約: 共通の型・演算条件を満たすこと。reset・clearは無効状態からの復旧にも使えます。

計算量: O(1)。値型・比較器のswapの費用は別です。

LinkCutTree<std::int64_t> tree(std::vector<std::int64_t>{2,4,1,7});
tree.link(0,1); tree.link(1,2); tree.link(1,3);
auto sum = tree.path_prod(2,3); // optionalに12が入る。1+4+7。
tree.cut(1,3);
auto missing = tree.path_prod(2,3); // nullopt。

同じ頂点へのパスでは集約値がその頂点の値、頂点数が1、辺数が0になります。パス操作・link・cutは根の向きを変える場合があります。根が重要ならmake_rootまたはlcaの引数で明示します。取得も補助木を変更するため非constです。

演算とパス更新

Opはconst呼出可能な結合演算、identityは左右の単位元です。左右の順序を保ち、写像合成などの非可換な集約も扱えます。T・Actionはcopyable、設定はconst呼出可能・move_constructibleで、破棄が例外を投げない型を使います。

パス更新にはLinkCutTree<T,Op,Action,Mapping,Composition>を指定します。Mappingはmapping(f,集約値,頂点数)で更新後の集約を返し、Compositionはcomposition(newer,older)でolderの後にnewerを適用する更新を返します。更新は集約へ分配でき、反転と可換であることが前提です。作用なしの型は更新用の状態を持ちません。

構築はO(N+1)時間・領域、森操作は償却O(log(N+1))、1回は最悪O(N+1)です。値・更新のコピーや演算をO(1)とします。数値は途中計算も値域内に収め、コールバックから同じ木へ再入しないでください。

所有権と検査

コピーは頂点・辺・遅延の領域が独立し、演算設定はconstで共有します。移動はnoexcept・O(1)、移動元は同じ設定の空の森として再利用できます。コピー代入・resetは確保やコピーの失敗時に元を保ちます。resetはO(旧N+新N+1)、clearはO(N+1)です。

森操作中に値・演算・更新等が例外を投げると、usable()==falseになります。reset・clear・代入で復旧するまで森操作はlogic_errorを投げます。失敗状態をコピー・移動した先も復旧が必要です。演算の外部状態は巻き戻しません。

頂点番号は既定で検査し、SKIP_RUNTIME_CHECKSで除きます。N<=INT_MAXの容量保護、接続・辺・順位による戻り値、例外後の無効化は常に維持します。番号の入力検査エラーでは無効化しません。

数学的参考はNyaanとLuzhiledです。実装は独立に組み立て、内部配置と検証結果は作業記録に置きます。

operator=

LinkCutTree& operator=(const LinkCutTree& other);
LinkCutTree& operator=(LinkCutTree&& other) noexcept;

コピーまたはムーブで内容を置き換え、自身への参照を返します。コピーは独立した内容を持ちます。

制約: 型・所有・例外保証は共通の説明に従います。

計算量: 保持する配列・ノードのコピーと旧内容の破棄に比例。ムーブ構築とは異なり、代入では旧内容の解放費用も含みます。

ソースのAPI注記
[LinkCutTree<T=int64_t, Op=plus<T>, Action=内部の作用なし型, Mapping=内部既定型, Composition=内部既定型>]
LinkCutTree(values={}, identity=T{}, op=Op{}, mapping=Mapping{}, composition=Composition{}): vector/spanの各値を持つ孤立頂点を構築。O(n+1)時間・領域。
Tはcopyable、Opはconst呼出可能な結合演算、identityは左右の単位元。非可換でも可。演算・コピー等をO(1)とする。
作用を使う場合はAction/Mapping/Compositionを指定。mapping(f,積,頂点数)、composition(new,old)はnewを後に作用。
作用は全頂点へ同じように適用でき、積に分配し、反転と可換であること。値・演算の数値範囲も利用者の前提。
値操作・演算・作用等から同じ木へ再入しない。
頂点は0..size()-1。n<=INT_MAX。以下の森操作は償却O(log(n+1))、1回は最悪O(n+1)。再帰しない。
link(u,v): 別成分なら辺を加えてtrue、閉路/自己辺ならfalse。cut(u,v): その辺があれば除いてtrue、なければfalse。
connected(u,v): 同じ成分か。make_root(v): vを成分の根にする。find_root(v): 現在の根の頂点番号。
get(v)/set(v,x)/transform(v,fn): 値をコピー/代入/fn(旧値)で更新。fnから同じ木へ再入しない。
path_prod(u,v): uからvへ端点を含め順に合成したoptional<T>。未接続ならnullopt。
path_size(u,v): パスの頂点数、未接続なら0。path_length(u,v): 辺数のoptional、未接続ならnullopt。
kth_on_path(u,v,k): u側から0始まりk番目の頂点。未接続/順位範囲外ならnullopt。
apply(v,f)/apply(u,v,f): 点/パス作用。作用あり型だけ。パス版は未接続なら変更せずfalse、成功true。
lca(root,u,v): rootを根にしたLCA。3頂点が同じ成分でなければnullopt。
パス操作・link/cutは根の向きを変える場合がある。根が重要ならmake_root/lcaで明示する。
size()/empty()/usable(): 頂点数/空か/例外後も森操作できるか。O(1)。reset(values): 同じ演算で孤立頂点へ再構築、O(旧n+n+1)。
clear(): 空へ戻して頂点領域を解放、O(n+1)。swap(other): O(1)。コピーは頂点/辺/遅延の領域が独立、演算設定はconst共有。
コピー/再構築の確保・コピー失敗時は元を保つ。moveはO(1)・noexcept、移動元は同じ設定の空の森として再利用できる。
森操作中に値操作/演算/作用が例外を送出したらusable()==false。以後はreset/clear/代入等で復旧するまで森操作不可。
値/Actionの失敗後も安全に破棄できること。外部状態は巻き戻さない。値/Actionはcopyable、設定はmove_constructibleで破棄はnoexcept。
添字検査だけをSKIP_RUNTIME_CHECKSで除く。容量・添字表現の上限、接続/辺/順位の戻り値、例外後の無効化は常に維持。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Dynamic Tree Vertex Add Path Sum link_cut_tree.cpp 未提出 —
Range Affine Range Sum link_cut_tree_affine.cpp 未提出 —
Dynamic Tree Vertex Set Path Composite link_cut_tree_composite.cpp 未提出 —

✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。

ローカル・CI検査

検査 状態
正常系 未実施
失敗系 未測定
Library Checker公式ケース 未測定
性能測定 未実施
ASan/UBSan 未実施
カバレッジ 未実施

到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。

実行条件・件数・測定結果 · 結果JSON

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 参考(数学的構成・機能): https://nyaannyaan.github.io/library/lct/link-cut-base.hpp
// 参考(数学的構成・機能): https://ei1333.github.io/library/structure/dynamic-tree/lazy-link-cut-tree.hpp
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/link_cut_tree.md
//
// API一覧
// [LinkCutTree<T=int64_t, Op=plus<T>, Action=内部の作用なし型, Mapping=内部既定型, Composition=内部既定型>]
// LinkCutTree(values={}, identity=T{}, op=Op{}, mapping=Mapping{}, composition=Composition{}): vector/spanの各値を持つ孤立頂点を構築。O(n+1)時間・領域。
// Tはcopyable、Opはconst呼出可能な結合演算、identityは左右の単位元。非可換でも可。演算・コピー等をO(1)とする。
// 作用を使う場合はAction/Mapping/Compositionを指定。mapping(f,積,頂点数)、composition(new,old)はnewを後に作用。
// 作用は全頂点へ同じように適用でき、積に分配し、反転と可換であること。値・演算の数値範囲も利用者の前提。
// 値操作・演算・作用等から同じ木へ再入しない。
// 頂点は0..size()-1。n<=INT_MAX。以下の森操作は償却O(log(n+1))、1回は最悪O(n+1)。再帰しない。
// link(u,v): 別成分なら辺を加えてtrue、閉路/自己辺ならfalse。cut(u,v): その辺があれば除いてtrue、なければfalse。
// connected(u,v): 同じ成分か。make_root(v): vを成分の根にする。find_root(v): 現在の根の頂点番号。
// get(v)/set(v,x)/transform(v,fn): 値をコピー/代入/fn(旧値)で更新。fnから同じ木へ再入しない。
// path_prod(u,v): uからvへ端点を含め順に合成したoptional<T>。未接続ならnullopt。
// path_size(u,v): パスの頂点数、未接続なら0。path_length(u,v): 辺数のoptional、未接続ならnullopt。
// kth_on_path(u,v,k): u側から0始まりk番目の頂点。未接続/順位範囲外ならnullopt。
// apply(v,f)/apply(u,v,f): 点/パス作用。作用あり型だけ。パス版は未接続なら変更せずfalse、成功true。
// lca(root,u,v): rootを根にしたLCA。3頂点が同じ成分でなければnullopt。
// パス操作・link/cutは根の向きを変える場合がある。根が重要ならmake_root/lcaで明示する。
// size()/empty()/usable(): 頂点数/空か/例外後も森操作できるか。O(1)。reset(values): 同じ演算で孤立頂点へ再構築、O(旧n+n+1)。
// clear(): 空へ戻して頂点領域を解放、O(n+1)。swap(other): O(1)。コピーは頂点/辺/遅延の領域が独立、演算設定はconst共有。
// コピー/再構築の確保・コピー失敗時は元を保つ。moveはO(1)・noexcept、移動元は同じ設定の空の森として再利用できる。
// 森操作中に値操作/演算/作用が例外を送出したらusable()==false。以後はreset/clear/代入等で復旧するまで森操作不可。
// 値/Actionの失敗後も安全に破棄できること。外部状態は巻き戻さない。値/Actionはcopyable、設定はmove_constructibleで破棄はnoexcept。
// 添字検査だけをSKIP_RUNTIME_CHECKSで除く。容量・添字表現の上限、接続/辺/順位の戻り値、例外後の無効化は常に維持。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <algorithm>
#include <limits>
#include <memory>
#include <optional>
#include <span>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_LINK_CUT_TREE_SUPPORT_DEFINED
#define SIRKIT_LINK_CUT_TREE_SUPPORT_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
struct NoLinkCutAction {};
template<class T> struct NoLinkCutMapping {
    T operator()(NoLinkCutAction, const T& value, std::size_t) const { return value; }
};
struct NoLinkCutComposition {
    NoLinkCutAction operator()(NoLinkCutAction, NoLinkCutAction) const noexcept { return {}; }
};
template<class Action, bool Enabled> struct LinkCutLazyState { std::optional<Action> pending; };
template<class Action> struct LinkCutLazyState<Action, false> {};
inline void CheckLinkCutCapacity(std::size_t n, std::size_t nodes, std::size_t ancestors) {
    const auto int_limit = static_cast<std::size_t>(std::numeric_limits<int>::max());
    if (n >= nodes || n > std::min(int_limit, ancestors)) throw std::length_error("LinkCutTree: capacity");
}
}
#endif

#ifndef SIRKIT_LINK_CUT_TREE_DEFINED
#define SIRKIT_LINK_CUT_TREE_DEFINED
template<class T = std::int64_t, class Op = std::plus<T>,
         class Action = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NoLinkCutAction,
         class Mapping = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NoLinkCutMapping<T>,
         class Composition = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NoLinkCutComposition>
class LinkCutTree {
    static constexpr bool has_action = !std::is_same_v<Action, /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NoLinkCutAction>;
    static_assert(std::copyable<T>);
    static_assert(has_action || (std::is_same_v<Mapping, /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NoLinkCutMapping<T>> && std::is_same_v<Composition, /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NoLinkCutComposition>), "LinkCutTree: specify Action with Mapping/Composition");
    static_assert(std::move_constructible<Op> && std::move_constructible<Mapping> && std::move_constructible<Composition>);
    static_assert(std::is_invocable_r_v<T, const Op&, const T&, const T&>);
    static_assert(!has_action || std::copyable<Action>);
    static_assert(!has_action || std::is_invocable_r_v<T, const Mapping&, const Action&, const T&, std::size_t>);
    static_assert(!has_action || std::is_invocable_r_v<Action, const Composition&, const Action&, const Action&>);
    struct Config {
        T identity;
        [[no_unique_address]] Op op;
        [[no_unique_address]] Mapping mapping;
        [[no_unique_address]] Composition composition;
        Config(const T& id, Op operation, Mapping map, Composition compose)
            : identity(id), op(std::move(operation)), mapping(std::move(map)), composition(std::move(compose)) {}
    };
    struct Node {
        int parent = 0, child[2]{0, 0};
        bool reversed = false;
        std::size_t count = 1;
        T value, forward, backward;
        [[no_unique_address]] /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::LinkCutLazyState<Action, has_action> lazy;
        explicit Node(const T& input, std::size_t length = 1)
            : count(length), value(input), forward(input), backward(input) {}
    };
    // 親子は非所有の配列添字。設定と頂点配列が所有する。
    std::shared_ptr<const Config> config_;
    std::vector<Node> nodes_;
    std::vector<int> ancestors_;
    std::size_t size_ = 0;
    bool failed_ = false;

    template<class Values> void initialize(const Values& values) {
        const auto n = values.size();
        detail::CheckLinkCutCapacity(n, nodes_.max_size(), ancestors_.max_size());
        nodes_.reserve(n + 1); ancestors_.reserve(n);
        nodes_.emplace_back(config_->identity, 0);
        for (std::size_t i = 0; i < n; ++i) nodes_.emplace_back(values[i]);
        size_ = n;
    }
    template<class Values> LinkCutTree(const Values& values, std::shared_ptr<const Config> config)
        : config_(std::move(config)) { initialize(values); }
    void check_vertex(int vertex) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (vertex < 0 || static_cast<std::size_t>(vertex) >= size_) throw std::out_of_range("LinkCutTree: vertex");
#else
        (void)vertex;
#endif
    }
    template<class Fn> decltype(auto) operate(Fn&& operation) {
        if (failed_) throw std::logic_error("LinkCutTree: reset required after exception");
        try { return std::forward<Fn>(operation)(); }
        catch (...) { failed_ = true; throw; }
    }
    bool auxiliary_root(int vertex) const noexcept {
        const int parent = nodes_[vertex].parent;
        return parent == 0 || (nodes_[parent].child[0] != vertex && nodes_[parent].child[1] != vertex);
    }
    void pull(int vertex) {
        auto& node = nodes_[vertex];
        const int left = node.child[0], right = node.child[1];
        node.count = nodes_[left].count + 1 + nodes_[right].count;
        T forward = left == 0 ? node.value : std::invoke(config_->op, nodes_[left].forward, node.value);
        if (right != 0) forward = std::invoke(config_->op, forward, nodes_[right].forward);
        T backward = right == 0 ? node.value : std::invoke(config_->op, nodes_[right].backward, node.value);
        if (left != 0) backward = std::invoke(config_->op, backward, nodes_[left].backward);
        node.forward = std::move(forward); node.backward = std::move(backward);
    }
    void reverse(int vertex) {
        if (vertex == 0) return;
        auto& node = nodes_[vertex];
        using std::swap;
        swap(node.child[0], node.child[1]); swap(node.forward, node.backward);
        node.reversed = !node.reversed;
    }
    void apply_node(int vertex, const Action& action) requires(has_action) {
        if (vertex == 0) return;
        auto& node = nodes_[vertex];
        T value = std::invoke(config_->mapping, action, node.value, std::size_t{1});
        T forward = std::invoke(config_->mapping, action, node.forward, node.count);
        T backward = std::invoke(config_->mapping, action, node.backward, node.count);
        std::optional<Action> pending;
        if (node.lazy.pending) pending.emplace(std::invoke(config_->composition, action, *node.lazy.pending));
        else pending.emplace(action);
        node.value = std::move(value); node.forward = std::move(forward); node.backward = std::move(backward);
        node.lazy.pending = std::move(pending);
    }
    void push(int vertex) {
        auto& node = nodes_[vertex];
        if (node.reversed) {
            reverse(node.child[0]); reverse(node.child[1]); node.reversed = false;
        }
        if constexpr (has_action) {
            if (node.lazy.pending) {
                apply_node(node.child[0], *node.lazy.pending); apply_node(node.child[1], *node.lazy.pending);
                node.lazy.pending.reset();
            }
        }
    }
    void rotate(int vertex) {
        const int parent = nodes_[vertex].parent, grandparent = nodes_[parent].parent;
        const int side = nodes_[parent].child[1] == vertex;
        const int middle = nodes_[vertex].child[side ^ 1];
        if (!auxiliary_root(parent)) nodes_[grandparent].child[nodes_[grandparent].child[1] == parent] = vertex;
        nodes_[vertex].parent = grandparent;
        nodes_[parent].child[side] = middle;
        if (middle != 0) nodes_[middle].parent = parent;
        nodes_[vertex].child[side ^ 1] = parent; nodes_[parent].parent = vertex;
        pull(parent); pull(vertex);
    }
    void splay(int vertex) {
        ancestors_.clear();
        int current = vertex;
        ancestors_.push_back(current);
        while (!auxiliary_root(current)) { current = nodes_[current].parent; ancestors_.push_back(current); }
        for (auto i = ancestors_.size(); i != 0; --i) push(ancestors_[i - 1]);
        while (!auxiliary_root(vertex)) {
            const int parent = nodes_[vertex].parent, grandparent = nodes_[parent].parent;
            if (!auxiliary_root(parent)) {
                if ((nodes_[parent].child[0] == vertex) == (nodes_[grandparent].child[0] == parent)) rotate(parent);
                else rotate(vertex);
            }
            rotate(vertex);
        }
    }
    int access(int vertex) {
        int last = 0;
        for (int current = vertex; current != 0; current = nodes_[current].parent) {
            splay(current);
            nodes_[current].child[1] = last;
            if (last != 0) nodes_[last].parent = current;
            pull(current); last = current;
        }
        splay(vertex); return last;
    }
    void make_root_impl(int vertex) { access(vertex); reverse(vertex); }
    int find_root_impl(int vertex) {
        access(vertex);
        for (;;) { push(vertex); if (nodes_[vertex].child[0] == 0) break; vertex = nodes_[vertex].child[0]; }
        splay(vertex); return vertex;
    }
    bool expose(int first, int last) {
        make_root_impl(first); access(last);
        // 接続していればfirstはlastの補助木内へ入り、別成分なら親0のまま。
        return first == last || nodes_[first].parent != 0;
    }
public:
    explicit LinkCutTree(std::span<const T> values = {}, const T& identity = T{}, Op op = Op{},
                         Mapping mapping = Mapping{}, Composition composition = Composition{})
        : config_(std::make_shared<Config>(identity, std::move(op), std::move(mapping), std::move(composition))) { initialize(values); }
    explicit LinkCutTree(const std::vector<T>& values, const T& identity = T{}, Op op = Op{},
                         Mapping mapping = Mapping{}, Composition composition = Composition{})
        : config_(std::make_shared<Config>(identity, std::move(op), std::move(mapping), std::move(composition))) { initialize(values); }
    LinkCutTree(const LinkCutTree& other)
        : config_(other.config_), nodes_(other.nodes_), size_(other.size_), failed_(other.failed_) { ancestors_.reserve(size_); }
    LinkCutTree& operator=(const LinkCutTree& other) {
        if (this != &other) { LinkCutTree replacement(other); swap(replacement); }
        return *this;
    }
    LinkCutTree(LinkCutTree&& other) noexcept
        : config_(other.config_), nodes_(std::move(other.nodes_)), ancestors_(std::move(other.ancestors_)),
          size_(std::exchange(other.size_, 0)), failed_(std::exchange(other.failed_, false)) {
        other.nodes_.clear(); other.ancestors_.clear();
    }
    LinkCutTree& operator=(LinkCutTree&& other) noexcept {
        if (this != &other) { LinkCutTree replacement(std::move(other)); swap(replacement); }
        return *this;
    }
    std::size_t size() const noexcept { return size_; }
    bool empty() const noexcept { return size_ == 0; }
    bool usable() const noexcept { return !failed_; }
    void reset(std::span<const T> values) { LinkCutTree replacement(values, config_); swap(replacement); }
    void reset(const std::vector<T>& values) { LinkCutTree replacement(values, config_); swap(replacement); }
    void clear() noexcept {
        std::vector<Node>().swap(nodes_); std::vector<int>().swap(ancestors_);
        size_ = 0; failed_ = false;
    }
    void swap(LinkCutTree& other) noexcept {
        config_.swap(other.config_); nodes_.swap(other.nodes_); ancestors_.swap(other.ancestors_);
        std::swap(size_, other.size_); std::swap(failed_, other.failed_);
    }
    friend void swap(LinkCutTree& first, LinkCutTree& second) noexcept { first.swap(second); }
    bool connected(int first, int last) {
        check_vertex(first); check_vertex(last);
        return operate([&] { return first == last || find_root_impl(first + 1) == find_root_impl(last + 1); });
    }
    void make_root(int vertex) { check_vertex(vertex); operate([&] { make_root_impl(vertex + 1); }); }
    int find_root(int vertex) { check_vertex(vertex); return operate([&] { return find_root_impl(vertex + 1) - 1; }); }
    bool link(int first, int last) {
        check_vertex(first); check_vertex(last);
        return operate([&] {
            const int u = first + 1, v = last + 1;
            if (expose(u, v)) return false;
            nodes_[u].parent = v; return true;
        });
    }
    bool cut(int first, int last) {
        check_vertex(first); check_vertex(last);
        return operate([&] {
            const int u = first + 1, v = last + 1;
            if (!expose(u, v) || nodes_[v].child[0] != u || nodes_[u].child[1] != 0) return false;
            nodes_[v].child[0] = 0; nodes_[u].parent = 0; pull(v); return true;
        });
    }
    T get(int vertex) {
        check_vertex(vertex);
        return operate([&] { access(vertex + 1); return nodes_[vertex + 1].value; });
    }
    void set(int vertex, const T& value) {
        check_vertex(vertex);
        operate([&] { const int u = vertex + 1; access(u); nodes_[u].value = value; pull(u); });
    }
    template<class Fn> void transform(int vertex, Fn&& function) {
        check_vertex(vertex);
        operate([&] {
            const int u = vertex + 1; access(u);
            nodes_[u].value = std::invoke(std::forward<Fn>(function), std::as_const(nodes_[u].value)); pull(u);
        });
    }
    std::optional<T> path_prod(int first, int last) {
        check_vertex(first); check_vertex(last);
        return operate([&]() -> std::optional<T> {
            if (!expose(first + 1, last + 1)) return std::nullopt;
            return nodes_[last + 1].forward;
        });
    }
    std::size_t path_size(int first, int last) {
        check_vertex(first); check_vertex(last);
        return operate([&] { return expose(first + 1, last + 1) ? nodes_[last + 1].count : std::size_t{0}; });
    }
    std::optional<std::size_t> path_length(int first, int last) {
        const auto count = path_size(first, last);
        return count == 0 ? std::nullopt : std::optional<std::size_t>(count - 1);
    }
    std::optional<int> kth_on_path(int first, int last, std::size_t k) {
        check_vertex(first); check_vertex(last);
        return operate([&]() -> std::optional<int> {
            if (!expose(first + 1, last + 1) || k >= nodes_[last + 1].count) return std::nullopt;
            int current = last + 1;
            for (;;) {
                push(current);
                const auto left = nodes_[nodes_[current].child[0]].count;
                if (k < left) current = nodes_[current].child[0];
                else if (k == left) { splay(current); return current - 1; }
                else { k -= left + 1; current = nodes_[current].child[1]; }
            }
        });
    }
    void apply(int vertex, const Action& action) requires(has_action) {
        transform(vertex, [&](const T& value) { return std::invoke(config_->mapping, action, value, std::size_t{1}); });
    }
    bool apply(int first, int last, const Action& action) requires(has_action) {
        check_vertex(first); check_vertex(last);
        return operate([&] {
            if (!expose(first + 1, last + 1)) return false;
            apply_node(last + 1, action); return true;
        });
    }
    std::optional<int> lca(int root, int first, int last) {
        check_vertex(root); check_vertex(first); check_vertex(last);
        return operate([&]() -> std::optional<int> {
            const int r = root + 1, u = first + 1, v = last + 1;
            make_root_impl(r);
            if (find_root_impl(u) != r || find_root_impl(v) != r) return std::nullopt;
            access(u); return access(v) - 1;
        });
    }
};
#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page