競技プログラミング用の C++ ライブラリ
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// monoid.hpp / group.hpp のモノイド・群と SegTree の細かい機能を愚直な実装とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する
#include "../../../src/algebra/monoid.hpp"
#include <array>
#include <deque>
#include <forward_list>
#include <iostream>
#include <limits>
#include <list>
#include <random>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "../../../src/algebra/group.hpp"
#include "../../../src/data_structures/dual-segtree.hpp"
#include "../../../src/data_structures/fenwick-tree.hpp"
#include "../../../src/data_structures/imos.hpp"
#include "../../../src/data_structures/lazy-segtree.hpp"
#include "../../../src/data_structures/link-cut-tree.hpp"
#include "../../../src/data_structures/monoid-unionfind.hpp"
#include "../../../src/data_structures/persistent-lazy-segtree.hpp"
#include "../../../src/data_structures/persistent-segtree.hpp"
#include "../../../src/data_structures/potentialized-unionfind.hpp"
#include "../../../src/data_structures/priority_counter.hpp"
#include "../../../src/data_structures/rbst.hpp"
#include "../../../src/data_structures/segtree-beats.hpp"
#include "../../../src/data_structures/segtree.hpp"
#include "../../../src/data_structures/sortable-segtree.hpp"
#include "../../../src/data_structures/sparse-table.hpp"
bool ok = true;
void check(bool cond, const char* what) {
if (!cond && ok) std::cerr << "failed: " << what << std::endl;
if (!cond) ok = false;
}
// SegTree<M> を、配列と演算 op で愚直に計算した結果とランダムな操作列で比べる
// size・const な operator[]・all_prod・os << seg も確かめる
template <typename M, typename Op, typename Gen>
void test_segtree(Op op, typename M::S e, Gen gen, std::mt19937_64& rng, const char* name) {
using S = typename M::S;
for (int rep = 0; rep < 200 && ok; rep++) {
int n = rng() % 20 + 1;
std::vector<S> a(n);
for (auto& x : a) x = gen();
SegTree<M> seg(a);
check(seg.size() == n, name);
for (int q = 0; q < 50 && ok; q++) {
int t = rng() % 3;
if (t == 0) {
int k = rng() % n;
S x = gen();
seg.set(k, x);
a[k] = x;
} else if (t == 1) {
int k = rng() % n;
S x = gen();
seg.apply(k, x);
a[k] = op(a[k], x);
} else {
int l = rng() % (n + 1), r = rng() % (n + 1);
if (l > r) std::swap(l, r);
S expect = e;
for (int i = l; i < r; i++) expect = op(expect, a[i]);
check(seg.prod(l, r) == expect, name);
}
}
S all = e;
for (int i = 0; i < n; i++) all = op(all, a[i]);
check(seg.all_prod() == all, name);
const SegTree<M>& cseg = seg;
std::ostringstream os, expect;
for (int i = 0; i < n; i++) {
check(cseg[i] == a[i], name);
if (i != 0) expect << ' ';
expect << a[i];
}
os << cseg;
check(os.str() == expect.str(), name);
}
}
struct ExplicitSum {
struct S {
long long value;
S() : value(0) {}
explicit S(long long x) : value(x) {}
};
static S op(const S& a, const S& b) { return S(a.value + b.value); }
static S e() { return S(0); }
};
struct ExplicitAddSum : ExplicitSum {
using F = long long;
static S mapping(F f, const S& x, long long len) { return S(x.value + f * len); }
static F composition(F f, F g) { return f + g; }
static F id() { return 0; }
static F inv(F f) { return -f; }
};
struct ExplicitGroup : ExplicitSum {
static S inv(const S& x) { return S(-x.value); }
};
struct ExplicitMin : ExplicitSum {
static S op(const S& a, const S& b) { return S(std::min(a.value, b.value)); }
static S e() { return S(std::numeric_limits<long long>::max()); }
};
struct ExplicitBeats : ExplicitAddSum {
static std::pair<bool, S> mapping(F f, const S& x, long long len) { return {false, ExplicitAddSum::mapping(f, x, len)}; }
};
// begin は一度だけ。イテレータの後置 ++ は値を返さず、終端の型も異なる。
struct SizedInputRange {
int values[3] = {2, -5, 4};
int pos = 0;
bool begun = false;
struct Sentinel {};
struct Iterator {
using value_type = int;
using difference_type = long long;
using iterator_category = std::input_iterator_tag;
SizedInputRange* range;
int operator*() const { return range->values[range->pos]; }
Iterator& operator++() {
++range->pos;
return *this;
}
void operator++(int) { ++*this; }
friend bool operator==(Iterator it, Sentinel) { return it.range->pos == 3; }
friend bool operator!=(Iterator it, Sentinel s) { return !(it == s); }
friend bool operator==(Sentinel s, Iterator it) { return it == s; }
friend bool operator!=(Sentinel s, Iterator it) { return !(it == s); }
};
Iterator begin() {
check(!begun, "sized input range is traversed once");
begun = true;
return {this};
}
Sentinel end() const { return {}; }
long long size() const { return 3; }
};
template <template <typename> class Tree, typename M>
void test_converting_tree(M m) {
auto verify_range = [&](auto&& r) {
Tree tree(std::forward<decltype(r)>(r), m);
check(tree.size() == 3 && tree.get(0).value == 2 && tree.get(1).value == -5 && tree.get(2).value == 4,
"tree family sized range / CTAD");
};
int raw[] = {2, -5, 4};
const std::array<int, 3> arr = {2, -5, 4};
verify_range(raw);
verify_range(arr);
verify_range(std::list<int>{2, -5, 4});
verify_range(std::deque<int>{2, -5, 4});
verify_range(SizedInputRange{});
Tree<M> empty_array(std::array<int, 0>{});
check(empty_array.size() == 0, "tree family empty array");
static_assert(!std::is_constructible_v<Tree<M>, std::forward_list<int>&>);
static_assert(!std::is_constructible_v<Tree<M>, std::array<std::string, 3>&>);
#if __cplusplus >= 202002L
verify_range(std::views::iota(0, 3) | std::views::transform([&](int i) { return raw[i]; }));
#endif
static_assert(std::is_constructible_v<Tree<M>, const std::vector<int>&, M>);
static_assert(!std::is_constructible_v<Tree<M>, const std::vector<std::string>&, M>);
Tree seg(std::vector<int>{2, -5, 4}, m);
check(seg.size() == 3 && seg.get(0).value == 2 && seg.get(1).value == -5 && seg.get(2).value == 4,
"segtree family explicit conversion / CTAD");
Tree<M> empty(std::vector<int>{});
check(empty.size() == 0, "segtree family conversion empty");
Tree<M> same(std::vector<typename M::S>{typename M::S(7)});
check(same.get(0).value == 7, "segtree family vector<S>");
Tree<M> list({typename M::S(8), typename M::S(9)});
check(list.get(1).value == 9, "segtree family initializer list");
}
template <class R>
void test_segtree_range(R&& r) {
SegTree seg(std::forward<R>(r), ExplicitSum{});
check(seg.size() == 3 && seg.prod(0, 3).value == 1 && seg.prod(1, 3).value == -1, "SegTree sized range / CTAD");
seg.set(1, ExplicitSum::S(3));
check(seg.all_prod().value == 9, "SegTree sized range update");
}
int main() {
{
using M = monoid::MinMax<>;
constexpr M::S single(7);
static_assert(single.min == 7 && single.max == 7);
static_assert(M::e() == M::S());
std::vector<long long> values = {3, -5, 8, 8, 0};
SegTree<M> seg(values);
for (long long l = 0; l <= 5; ++l) {
for (long long r = l; r <= 5; ++r) {
long long mn = std::numeric_limits<long long>::max(), mx = std::numeric_limits<long long>::lowest();
for (long long i = l; i < r; ++i) {
mn = std::min(mn, values[i]);
mx = std::max(mx, values[i]);
}
auto [actual_min, actual_max] = seg.prod(l, r);
check(actual_min == mn && actual_max == mx, "MinMax members and structured binding");
check(seg.prod(l, r) == M::S(mn, mx), "MinMax equality");
check(M::op(M::e(), seg.prod(l, r)) == seg.prod(l, r) && M::op(seg.prod(l, r), M::e()) == seg.prod(l, r), "MinMax identity");
}
}
check(!(M::S(1) != M::S(1)) && M::S(1) != M::S(2), "MinMax inequality");
using A = acted_monoid::ClampMinMax<long long>;
using B = acted_monoid::ClampAddMinMax<long long>;
check(A::mapping({0, 10}, M::e()) == M::e(), "ClampMinMax empty");
check(B::mapping({{}, {}, 3}, M::e()) == M::e(), "ClampAddMinMax empty");
}
{
int a[] = {2, -5, 4};
const std::array<int, 3> b = {2, -5, 4};
test_segtree_range(a);
test_segtree_range(b);
test_segtree_range(std::list<int>{2, -5, 4});
test_segtree_range(std::deque<int>{2, -5, 4});
SegTree<ExplicitSum> empty(std::array<int, 0>{});
check(empty.size() == 0 && empty.all_prod().value == 0, "SegTree empty range");
SegTree braces({ExplicitSum::S(2), ExplicitSum::S(-5), ExplicitSum::S(4)}, ExplicitSum{});
check(braces.all_prod().value == 1, "SegTree initializer list / CTAD");
SegTree<ExplicitSum> original(a);
auto copied = original;
auto moved = std::move(copied);
check(moved.all_prod().value == 1 && original.all_prod().value == 1, "SegTree copy / move");
SegTree sized(3LL, ExplicitSum{});
check(sized.size() == 3 && sized.all_prod().value == 0, "SegTree size / CTAD");
static_assert(!std::is_constructible_v<SegTree<ExplicitSum>, std::forward_list<int>&>);
static_assert(!std::is_constructible_v<SegTree<ExplicitSum>, std::array<std::string, 3>&>);
#if __cplusplus >= 202002L
test_segtree_range(std::views::all(a));
test_segtree_range(std::views::iota(0, 3) | std::views::transform([&](int i) { return a[i]; }));
SegTree view(a | std::views::take(2), ExplicitSum{});
check(view.size() == 2 && view.all_prod().value == -3, "SegTree partial view");
#endif
}
test_converting_tree<SegTree>(ExplicitSum{});
test_converting_tree<RBST>(ExplicitSum{});
test_converting_tree<RBST>(ExplicitAddSum{});
test_converting_tree<FenwickTree>(ExplicitGroup{});
test_converting_tree<SparseTable>(ExplicitMin{});
test_converting_tree<LinkCutTree>(ExplicitSum{});
test_converting_tree<SubtreeLinkCutTree>(ExplicitGroup{});
{
auto verify = [](auto&& r) {
MonoidUnionFind uf(std::forward<decltype(r)>(r), ExplicitSum{});
uf.merge(0, 1);
check(uf.prod(0).value == -3 && uf.prod(2).value == 4, "MonoidUnionFind sized range / CTAD");
};
int raw[] = {2, -5, 4};
verify(raw);
verify(std::list<int>{2, -5, 4});
verify(SizedInputRange{});
std::vector<ExplicitSum::S> owned{ExplicitSum::S(7)};
const auto* ptr = owned.data();
MonoidUnionFind moved(std::move(owned), ExplicitSum{});
check(&moved.prod(0) == ptr, "MonoidUnionFind moves vector storage");
Imos from_range(SizedInputRange{}, ExplicitAddSum{});
from_range.apply(0, 2, 3);
check(from_range.get(0).value == 5 && from_range.get(1).value == -2 && from_range.get(2).value == 4,
"Imos sized input range / CTAD");
Imos from_list(std::list<int>{2, -5, 4}, ExplicitAddSum{});
check(from_list.get(1).value == -5, "Imos list");
Imos<ExplicitAddSum> empty_range(std::array<int, 0>{});
static_assert(!std::is_constructible_v<Imos<ExplicitAddSum>, std::forward_list<int>&>);
static_assert(!std::is_constructible_v<MonoidUnionFind<ExplicitSum>, const std::vector<std::string>&>);
MonoidUnionFind uf(std::vector<int>{2, -5, 4}, ExplicitSum{});
uf.merge(0, 1);
check(uf.prod(0).value == -3 && uf.prod(2).value == 4, "MonoidUnionFind conversion / CTAD");
MonoidUnionFind<ExplicitSum> empty(std::vector<int>{});
check(empty.groups().empty(), "MonoidUnionFind conversion empty");
Imos imos(std::vector<int>{2, -5, 4}, ExplicitAddSum{});
imos.apply(0, 2, 3);
check(imos.get(0).value == 5 && imos.get(1).value == -2 && imos.get(2).value == 4, "Imos conversion / CTAD");
Imos<ExplicitAddSum> empty_imos(std::vector<int>{});
static_assert(!std::is_constructible_v<Imos<ExplicitAddSum>, const std::vector<std::string>&>);
}
test_converting_tree<LazySegTree>(ExplicitAddSum{});
test_converting_tree<DualSegTree>(ExplicitAddSum{});
test_converting_tree<PersistentSegTree>(ExplicitSum{});
test_converting_tree<PersistentLazySegTree>(ExplicitAddSum{});
test_converting_tree<SegTreeBeats>(ExplicitBeats{});
{
auto verify = [](auto&& keys, auto&& values) {
SortableSegTree tree(std::forward<decltype(keys)>(keys), std::forward<decltype(values)>(values), 3, ExplicitSum{});
tree.sort(0, 3);
check(tree.prod(0, 1).value == -5 && tree.prod(0, 3).value == 1, "SortableSegTree sized ranges / sort / CTAD");
};
int keys[] = {2, 0, 1};
verify(keys, std::list<int>{2, -5, 4});
verify(std::list<int>{2, 0, 1}, SizedInputRange{});
SortableSegTree braces({2, 0, 1}, {ExplicitSum::S(2), ExplicitSum::S(-5), ExplicitSum::S(4)}, 3, ExplicitSum{});
check(braces.prod(0, 3).value == 1, "SortableSegTree initializer lists / CTAD");
SortableSegTree sorted(std::vector<long long>{2, 0, 1}, std::vector<int>{2, -5, 4}, 3, ExplicitSum{});
sorted.sort(0, 3);
check(sorted.prod(0, 1).value == -5 && sorted.prod(0, 3).value == 1, "SortableSegTree conversion / CTAD / sort");
SortableSegTree<ExplicitSum> empty(std::vector<long long>{}, std::vector<int>{}, 1);
check(empty.size() == 0, "SortableSegTree conversion empty");
}
{
static_assert(std::is_constructible_v<SegTree<ExplicitSum>, const std::vector<int>&>);
static_assert(!std::is_constructible_v<SegTree<ExplicitSum>, const std::vector<std::string>&>);
SegTree seg(std::vector<int>{2, -5, 4}, ExplicitSum{});
check(seg.prod(0, 3).value == 1 && seg.prod(1, 3).value == -1, "SegTree explicit conversion / CTAD");
SegTree<ExplicitSum> empty(std::vector<int>{});
check(empty.size() == 0 && empty.all_prod().value == 0, "SegTree conversion empty");
SegTree<monoid::Sum<long long>> ordinary({1, 2, 3});
check(ordinary.all_prod() == 6, "SegTree initializer list");
SegTree<monoid::Sum<long long>> widened(std::vector<int>{1, 2, 3});
check(widened.all_prod() == 6, "SegTree arithmetic conversion");
}
{
using PC = MaxCounter<int, 3>;
using M = monoid::Sum<PC>;
static_assert(M::e().size() == 0);
static_assert(group::Sum<long long>::e() == 0);
SegTree<M> empty(3);
check(empty.all_prod().size() == 0, "Sum<PriorityCounter> 初期値は空");
SegTree<M> seg(std::vector<int>{-5, -5, -2});
const std::vector<int> values = {-5, -5, -2};
for (long long l = 0; l <= 3; l++) {
for (long long r = l; r <= 3; r++) {
PC expect;
for (long long i = l; i < r; i++) expect.inc(values[i]);
const auto actual = seg.prod(l, r);
check(actual.size() == expect.size(), "Sum<PriorityCounter> 種類数");
for (long long i = 0; i < 3; i++) {
check(actual[i].second == expect[i].second, "Sum<PriorityCounter> 個数");
if (expect[i].second) check(actual[i].first == expect[i].first, "Sum<PriorityCounter> 値");
}
}
}
}
std::mt19937_64 rng(314);
// And / Or: 単位元はそれぞれ全ビット 1 と 0
check(monoid::And<unsigned>::e() == ~0u, "And::e");
check(monoid::Or<unsigned>::e() == 0u, "Or::e");
auto gen_bits = [&] { return static_cast<unsigned>(rng() % 64); };
test_segtree<monoid::And<unsigned>>([](unsigned a, unsigned b) { return a & b; }, ~0u, gen_bits, rng, "And");
test_segtree<monoid::Or<unsigned>>([](unsigned a, unsigned b) { return a | b; }, 0u, gen_bits, rng, "Or");
// Parenthesis: 区間が正しい括弧列かを is_valid で判定する
for (int rep = 0; rep < 300 && ok; rep++) {
int n = rng() % 16 + 1;
std::string s(n, '(');
for (char& c : s) c = rng() % 2 ? '(' : ')';
SegTree<monoid::Parenthesis> seg(s);
for (int l = 0; l <= n; l++) {
for (int r = l; r <= n; r++) {
int depth = 0, min_depth = 0;
for (int i = l; i < r; i++) {
depth += s[i] == '(' ? 1 : -1;
min_depth = std::min(min_depth, depth);
}
auto p = seg.prod(l, r);
check(p.is_valid() == (depth == 0 && min_depth == 0), "Parenthesis::is_valid");
check(p.close == -min_depth && p.open == depth - min_depth, "Parenthesis::op");
}
}
}
// Affine: ==, !=, 出力
{
Affine<long long> f{2, 3}, g{2, 3}, h{2, 4}, id;
check(f == g && !(f != g), "Affine ==");
check(f != h && !(f == h), "Affine !=");
check(id == Affine<long long>{1, 0}, "Affine default");
std::ostringstream os;
os << f;
check(os.str() == "2 3", "Affine <<");
// Composite で合成した結果が関数の合成 a∘b と一致する。Reverse は b∘a
for (int rep = 0; rep < 1000 && ok; rep++) {
Affine<long long> a{static_cast<long long>(rng() % 7) - 3, static_cast<long long>(rng() % 7) - 3};
Affine<long long> b{static_cast<long long>(rng() % 7) - 3, static_cast<long long>(rng() % 7) - 3};
long long x = static_cast<long long>(rng() % 7) - 3;
auto c = monoid::Composite<long long>::op(a, b);
check(c(x) == a(b(x)), "Composite op");
check(c == Affine<long long>{a.a * b.a, a.a * b.b + a.b}, "Affine == after op");
auto d = monoid::Reverse<monoid::Composite<long long>>().op(a, b);
check(d(x) == b(a(x)), "Reverse<Composite> op");
}
}
// Clamp: ==, !=, 入出力, 既定値は恒等写像
{
Clamp<long long> f{2, 5}, g{2, 5}, h{2, 6}, id;
check(f == g && !(f != g), "Clamp ==");
check(f != h && !(f == h), "Clamp !=");
check(id(std::numeric_limits<long long>::lowest()) == std::numeric_limits<long long>::lowest() && id(std::numeric_limits<long long>::max()) == std::numeric_limits<long long>::max(), "Clamp default");
check(f(1) == 2 && f(3) == 3 && f(9) == 5, "Clamp ()");
// {} を渡すと下限・上限なし。1 つの値からは暗黙に変換しない
check((Clamp<long long>{0, {}} == Clamp<long long>{0, std::numeric_limits<long long>::max()}), "Clamp {lb, {}}");
check((Clamp<long long>{{}, 0} == Clamp<long long>{std::numeric_limits<long long>::lowest(), 0}), "Clamp {{}, ub}");
check((Clamp<long long>{{}, {}} == Clamp<long long>{}), "Clamp {{}, {}}");
static_assert(!std::is_convertible_v<long long, Clamp<long long>>);
static_assert(std::is_trivially_copyable_v<Clamp<long long>>);
static_assert(Clamp<int>{0, {}}(-5) == 0);
std::ostringstream os;
os << f;
check(os.str() == "2 5", "Clamp <<");
std::istringstream is("-3 4");
is >> f;
check(f == Clamp<long long>{-3, 4}, "Clamp >>");
// ClampComposite で合成した結果が関数の合成 a∘b と一致する。Reverse は b∘a
auto gen_clamp = [&] {
long long lb = static_cast<long long>(rng() % 11) - 5, ub = static_cast<long long>(rng() % 11) - 5;
if (lb > ub) std::swap(lb, ub);
if (rng() % 4 == 0) lb = std::numeric_limits<long long>::lowest();
if (rng() % 4 == 0) ub = std::numeric_limits<long long>::max();
return Clamp<long long>{lb, ub};
};
for (int rep = 0; rep < 1000 && ok; rep++) {
auto a = gen_clamp(), b = gen_clamp();
auto c = monoid::ClampComposite<long long>::op(a, b);
auto d = monoid::Reverse<monoid::ClampComposite<long long>>().op(a, b);
check(c.lb <= c.ub, "ClampComposite lb <= ub");
check(monoid::ClampComposite<long long>::op(a, monoid::ClampComposite<long long>::e()) == a, "ClampComposite e");
check(monoid::ClampComposite<long long>::op(monoid::ClampComposite<long long>::e(), a) == a, "ClampComposite e");
for (long long x = -7; x <= 7; x++) {
check(c(x) == a(b(x)), "ClampComposite op");
check(d(x) == b(a(x)), "Reverse<ClampComposite> op");
}
}
// SegTree に乗せて、区間の関数を右から順に適用した結果と比べる
test_segtree<monoid::ClampComposite<long long>>(
[](const Clamp<long long>& a, const Clamp<long long>& b) { return monoid::ClampComposite<long long>::op(a, b); },
Clamp<long long>{}, gen_clamp, rng, "ClampComposite");
}
// ClampAdd: ==, !=, 入出力, 既定値は恒等写像
{
constexpr long long lowest = std::numeric_limits<long long>::lowest(), highest = std::numeric_limits<long long>::max();
ClampAdd<long long> f{2, 5, 1}, g{2, 5, 1}, h{2, 5, 0}, id;
check(f == g && !(f != g), "ClampAdd ==");
check(f != h && !(f == h), "ClampAdd !=");
check(id == ClampAdd<long long>{lowest, highest, 0} && id(lowest) == lowest && id(highest) == highest, "ClampAdd default");
check(f(0) == 2 && f(2) == 3 && f(9) == 5, "ClampAdd ()");
// {} を渡すと下限・上限なし。add は省略すると 0。1 つの値からは暗黙に変換しない
check((ClampAdd<long long>{{}, {}, 3} == ClampAdd<long long>{lowest, highest, 3}), "ClampAdd {{}, {}, add}");
check((ClampAdd<long long>{{}, 5} == ClampAdd<long long>{lowest, 5, 0}), "ClampAdd {{}, ub}");
check((ClampAdd<long long>{5, {}} == ClampAdd<long long>{5, highest, 0}), "ClampAdd {lb, {}}");
static_assert(!std::is_convertible_v<long long, ClampAdd<long long>>);
static_assert(std::is_trivially_copyable_v<ClampAdd<long long>>);
static_assert(ClampAdd<int>{{}, 10, 3}(9) == 10);
std::ostringstream os;
os << f;
check(os.str() == "2 5 1", "ClampAdd <<");
std::istringstream is("-3 4 -1");
is >> f;
check(f == ClampAdd<long long>{-3, 4, -1}, "ClampAdd >>");
// ClampAddComposite で合成した結果が関数の合成 a∘b と一致する。Reverse は b∘a
// 下限・上限なし (型の最小値・最大値) に足してもあふれない (UBSan で確かめる)
auto gen_clamp_add = [&] {
long long lb = static_cast<long long>(rng() % 11) - 5, ub = static_cast<long long>(rng() % 11) - 5;
if (lb > ub) std::swap(lb, ub);
if (rng() % 3 == 0) lb = lowest;
if (rng() % 3 == 0) ub = highest;
return ClampAdd<long long>{lb, ub, static_cast<long long>(rng() % 7) - 3};
};
for (int rep = 0; rep < 1000 && ok; rep++) {
auto a = gen_clamp_add(), b = gen_clamp_add();
auto c = monoid::ClampAddComposite<long long>::op(a, b);
auto d = monoid::Reverse<monoid::ClampAddComposite<long long>>().op(a, b);
check(c.lb <= c.ub, "ClampAddComposite lb <= ub");
check(monoid::ClampAddComposite<long long>::op(a, monoid::ClampAddComposite<long long>::e()) == a, "ClampAddComposite e");
check(monoid::ClampAddComposite<long long>::op(monoid::ClampAddComposite<long long>::e(), a) == a, "ClampAddComposite e");
for (long long x = -9; x <= 9; x++) {
check(c(x) == a(b(x)), "ClampAddComposite op");
check(d(x) == b(a(x)), "Reverse<ClampAddComposite> op");
}
}
// SegTree に乗せる (加算が積み重なってもあふれない範囲で)
test_segtree<monoid::ClampAddComposite<long long>>(
[](const ClampAdd<long long>& a, const ClampAdd<long long>& b) { return monoid::ClampAddComposite<long long>::op(a, b); },
ClampAdd<long long>{}, gen_clamp_add, rng, "ClampAddComposite");
}
// group::Xor: inv は自分自身。PotentializedUnionFind に乗せて xor のポテンシャルと比べる
for (int rep = 0; rep < 300 && ok; rep++) {
int n = rng() % 12 + 1;
std::vector<int> pot(n);
for (int& p : pot) p = rng() % 1024;
std::vector<int> comp(n);
for (int i = 0; i < n; i++) comp[i] = i;
PotentializedUnionFind<group::Xor<int>> uf(n);
for (int q = 0; q < 30 && ok; q++) {
int a = rng() % n, b = rng() % n;
if (rng() % 2) {
uf.merge(a, b, pot[a] ^ pot[b]);
int ca = comp[a], cb = comp[b];
for (int& c : comp)
if (c == cb) c = ca;
} else {
check(uf.same(a, b) == (comp[a] == comp[b]), "group::Xor same");
if (comp[a] == comp[b]) check(uf.diff(a, b) == (pot[a] ^ pot[b]), "group::Xor diff");
}
}
int x = rng() % 1024;
check(group::Xor<int>::inv(x) == x, "group::Xor::inv");
}
// PrefixSumMax / PrefixSumMin / PrefixSumMinMax / SuffixSumMax / SuffixSumMin / MaxSubarraySum: 空を含む prefix・suffix・部分配列の和
for (int rep = 0; rep < 300 && ok; rep++) {
int n = rng() % 12 + 1;
std::vector<long long> a(n);
for (auto& x : a) x = static_cast<long long>(rng() % 21) - 10;
SegTree<monoid::PrefixSumMax<long long>> pmax(a);
SegTree<monoid::PrefixSumMin<long long>> pmin(a);
using PM = monoid::PrefixSumMinMax<>;
SegTree<PM> pminmax(a);
SegTree<monoid::SuffixSumMax<long long>> smax(a);
SegTree<monoid::SuffixSumMin<long long>> smin(a);
SegTree<monoid::MaxSubarraySum<long long>> msub(a);
for (int q = 0; q < 10 && ok; q++) {
int k = rng() % n;
a[k] = static_cast<long long>(rng() % 21) - 10;
pminmax.set(k, a[k]);
pmax.set(k, a[k]), pmin.set(k, a[k]), smax.set(k, a[k]), smin.set(k, a[k]), msub.set(k, a[k]);
for (int l = 0; l <= n; l++) {
for (int r = l; r <= n; r++) {
long long sum = 0, pre_max = 0, pre_min = 0, suf_max = 0, suf_min = 0, best = 0;
for (int i = l; i < r; i++) {
sum += a[i];
pre_max = std::max(pre_max, sum), pre_min = std::min(pre_min, sum);
long long s = 0;
for (int j = i; j < r; j++) {
s += a[j];
best = std::max(best, s);
}
}
long long s = 0;
for (int i = r - 1; i >= l; i--) {
s += a[i];
suf_max = std::max(suf_max, s), suf_min = std::min(suf_min, s);
}
check(pmax.prod(l, r) == monoid::PrefixSumMax<long long>::S(sum, pre_max), "PrefixSumMax");
check(pmin.prod(l, r) == monoid::PrefixSumMin<long long>::S(sum, pre_min), "PrefixSumMin");
check(pminmax.prod(l, r) == PM::S(sum, pre_min, pre_max), "PrefixSumMinMax");
check(PM::op(PM::e(), pminmax.prod(l, r)) == pminmax.prod(l, r) &&
PM::op(pminmax.prod(l, r), PM::e()) == pminmax.prod(l, r),
"PrefixSumMinMax identity");
int m = (l + r) / 2;
check(PM::op(pminmax.prod(l, m), pminmax.prod(m, r)) == pminmax.prod(l, r), "PrefixSumMinMax concatenate");
check(smax.prod(l, r) == monoid::SuffixSumMax<long long>::S(sum, suf_max), "SuffixSumMax");
check(smin.prod(l, r) == monoid::SuffixSumMin<long long>::S(sum, suf_min), "SuffixSumMin");
check(msub.prod(l, r) == monoid::MaxSubarraySum<long long>::S(sum, pre_max, suf_max, best), "MaxSubarraySum");
}
}
// max_right: l から始めて和が初めて正になる位置
int l = rng() % (n + 1);
long long sum = 0;
int expect = n;
for (int i = l; i < n; i++) {
sum += a[i];
if (sum > 0) {
expect = i;
break;
}
}
check(pmax.max_right(l, [](const auto& s) { return s.max <= 0; }) == expect, "PrefixSumMax max_right");
}
}
// MinWith / MaxWith: 空区間は位置 -1。値が型の最大値 (最小値) の要素があっても単位元として働き、同じ値なら左側
{
using Mn = monoid::MinWith<long long>;
using Mx = monoid::MaxWith<long long>;
constexpr long long INF = std::numeric_limits<long long>::max(), NINF = std::numeric_limits<long long>::lowest();
check(Mn::e() == std::pair<long long, long long>(INF, -1) && Mx::e() == std::pair<long long, long long>(NINF, -1), "MinWith/MaxWith::e");
check(Mn::op(Mn::e(), {INF, 3}) == std::pair<long long, long long>(INF, 3) && Mn::op({INF, 3}, Mn::e()) == std::pair<long long, long long>(INF, 3), "MinWith e は単位元");
check(Mx::op(Mx::e(), {NINF, 3}) == std::pair<long long, long long>(NINF, 3) && Mx::op({NINF, 3}, Mx::e()) == std::pair<long long, long long>(NINF, 3), "MaxWith e は単位元");
for (int rep = 0; rep < 200 && ok; rep++) {
int n = rng() % 20 + 1;
std::vector<long long> a(n);
for (auto& x : a) x = rng() % 3 == 0 ? (rng() % 2 ? INF : NINF) : static_cast<long long>(rng() % 5);
std::vector<std::pair<long long, long long>> init(n);
for (int i = 0; i < n; i++) init[i] = {a[i], i};
SegTree<Mn> mn(init);
SegTree<Mx> mx(init);
for (int q = 0; q < 30; q++) {
int l = rng() % (n + 1), r = rng() % (n + 1);
if (l > r) std::swap(l, r);
std::pair<long long, long long> emn(INF, -1), emx(NINF, -1);
for (int i = l; i < r; i++) {
if (emn.second == -1 || a[i] < emn.first) emn = {a[i], i};
if (emx.second == -1 || a[i] > emx.first) emx = {a[i], i};
}
check(mn.prod(l, r) == emn, "MinWith prod");
check(mx.prod(l, r) == emx, "MaxWith prod");
}
}
}
if (ok) std::cout << "Hello World" << std::endl;
}#line 1 "test/unittest/algebra/monoid.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// monoid.hpp / group.hpp のモノイド・群と SegTree の細かい機能を愚直な実装とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する
#line 2 "src/algebra/monoid.hpp"
/**
* @file monoid.hpp
* @brief モノイドの定義
*
* モノイドは次のメンバを持つ型として表す
* - using S: 要素の型
* - S op(const S& a, const S& b): 積 (結合的)
* - S e(): 単位元
* op, e は static でも非 static でもよい (データ構造はモノイドのオブジェクトを保持して呼び出す)
*/
#include <algorithm>
#include <array>
#include <cstddef>
#include <istream>
#include <limits>
#include <numeric>
#include <optional>
#include <ostream>
#include <type_traits>
#include <utility>
/**
* @brief 1次関数 f(x) = a * x + b
*
* monoid::Composite の要素や acted_monoid::AffineSum の作用素に使う
* 例: Affine<mint> f{2, 3}; f(x) は 2x + 3。省略すると恒等写像 {1, 0}
*/
template <typename T>
struct Affine {
T a = T(1); //!< 傾き
T b = T(0); //!< 切片
constexpr T operator()(const T& x) const { return a * x + b; }
friend constexpr bool operator==(const Affine& f, const Affine& g) { return f.a == g.a && f.b == g.b; }
friend constexpr bool operator!=(const Affine& f, const Affine& g) { return !(f == g); }
template <class CharT, class Traits>
friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Affine& f) {
return is >> f.a >> f.b;
}
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Affine& f) {
return os << f.a << CharT(' ') << f.b;
}
};
/**
* @brief clamp する関数 f(x) = min(max(x, lb), ub)
*
* monoid::ClampComposite の要素や acted_monoid::ClampMin などの作用素に使う
* 例: Clamp<int> f{0, 10}; f(x) は x を [0, 10] に収める。省略すると恒等写像 {型の最小値, 型の最大値}
* lb, ub に {} (std::nullopt) を渡すと下限・上限なし (型の最小値・最大値) になる。例: Clamp<int>{0, {}} は chmax 0
* lb <= ub でなければならない
*/
template <typename T>
struct Clamp {
T lb; //!< 下限
T ub; //!< 上限
/// @brief 恒等写像
constexpr Clamp() : lb(std::numeric_limits<T>::lowest()), ub(std::numeric_limits<T>::max()) {}
/// @brief 1 つの値からの暗黙の変換を防ぐため、lb と ub は両方渡す
constexpr Clamp(std::optional<T> _lb, std::optional<T> _ub)
: lb(_lb ? *_lb : std::numeric_limits<T>::lowest()), ub(_ub ? *_ub : std::numeric_limits<T>::max()) {}
constexpr T operator()(const T& x) const { return std::min(std::max(x, lb), ub); }
friend constexpr bool operator==(const Clamp& f, const Clamp& g) { return f.lb == g.lb && f.ub == g.ub; }
friend constexpr bool operator!=(const Clamp& f, const Clamp& g) { return !(f == g); }
template <class CharT, class Traits>
friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Clamp& f) {
return is >> f.lb >> f.ub;
}
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Clamp& f) {
return os << f.lb << CharT(' ') << f.ub;
}
};
/**
* @brief 足してから clamp する関数 f(x) = min(max(x + add, lb), ub)
*
* monoid::ClampAddComposite の要素や acted_monoid::ClampAddMin、beats_acted_monoid::ChminChmaxAddSum の作用素に使う
* 例: ClampAdd<long long> f{0, 10, 3}; f(x) は x + 3 を [0, 10] に収める。省略すると恒等写像 {型の最小値, 型の最大値, 0}
* lb <= ub でなければならない。lb が型の最小値、ub が型の最大値のときは、それぞれ下限・上限がないことを表す
* lb, ub に {} (std::nullopt) を渡すと下限・上限なしになる。例: ClampAdd<long long>{{}, {}, 3} は 3 を足す、{{}, 5} は chmin 5
*/
template <typename T>
struct ClampAdd {
T lb; //!< 下限
T ub; //!< 上限
T add; //!< clamp の前に足す値
/// @brief 恒等写像
constexpr ClampAdd() : lb(std::numeric_limits<T>::lowest()), ub(std::numeric_limits<T>::max()), add(T(0)) {}
/// @brief 1 つの値からの暗黙の変換を防ぐため、lb と ub は両方渡す
constexpr ClampAdd(std::optional<T> _lb, std::optional<T> _ub, T _add = T(0))
: lb(_lb ? *_lb : std::numeric_limits<T>::lowest()), ub(_ub ? *_ub : std::numeric_limits<T>::max()), add(_add) {}
constexpr T operator()(const T& x) const { return std::min(std::max(x + add, lb), ub); }
friend constexpr bool operator==(const ClampAdd& f, const ClampAdd& g) { return f.lb == g.lb && f.ub == g.ub && f.add == g.add; }
friend constexpr bool operator!=(const ClampAdd& f, const ClampAdd& g) { return !(f == g); }
template <class CharT, class Traits>
friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, ClampAdd& f) {
return is >> f.lb >> f.ub >> f.add;
}
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const ClampAdd& f) {
return os << f.lb << CharT(' ') << f.ub << CharT(' ') << f.add;
}
};
namespace internal_monoid {
// MinWith・MaxWith の単位元の位置。U が bool 以外の整数型なら -1 (実在の位置と区別できる)、そうでなければ U{}
template <typename U>
constexpr bool with_has_e_position = std::is_integral_v<U> && !std::is_same_v<U, bool>;
template <typename U>
constexpr U with_e_position() {
if constexpr (with_has_e_position<U>)
return static_cast<U>(-1);
else
return U{};
}
// U が bool 以外の整数型で、位置が -1 なら単位元
template <typename U>
constexpr bool with_is_e(const U& u) {
if constexpr (with_has_e_position<U>)
return u == static_cast<U>(-1);
else
return false;
}
} // namespace internal_monoid
namespace monoid {
/**
* @brief 和
*/
template <typename T>
struct Sum {
using S = T;
static constexpr S op(const S& a, const S& b) { return a + b; }
static constexpr S e() { return S{}; }
};
/**
* @brief 積
*/
template <typename T>
struct Prod {
using S = T;
static constexpr S op(const S& a, const S& b) { return a * b; }
static constexpr S e() { return S(1); }
};
/**
* @brief 最大値 単位元は型の最小値
*/
template <typename T>
struct Max {
using S = T;
static constexpr S op(const S& a, const S& b) { return std::max(a, b); }
static constexpr S e() { return std::numeric_limits<S>::lowest(); }
};
/**
* @brief 最小値 単位元は型の最大値
*/
template <typename T>
struct Min {
using S = T;
static constexpr S op(const S& a, const S& b) { return std::min(a, b); }
static constexpr S e() { return std::numeric_limits<S>::max(); }
};
/**
* @brief 最小値と最大値の組 {min, max}
*/
template <typename T = long long>
struct MinMax {
struct S {
T min, max;
constexpr S() : min(std::numeric_limits<T>::max()), max(std::numeric_limits<T>::lowest()) {}
constexpr S(const T& x) : min(x), max(x) {}
constexpr S(const T& min, const T& max) : min(min), max(max) {}
friend constexpr bool operator==(const S& a, const S& b) { return a.min == b.min && a.max == b.max; }
friend constexpr bool operator!=(const S& a, const S& b) { return !(a == b); }
};
static constexpr S op(const S& a, const S& b) { return {std::min(a.min, b.min), std::max(a.max, b.max)}; }
static constexpr S e() { return S(); }
};
/**
* @brief 排他的論理和
*/
template <typename T>
struct Xor {
using S = T;
static constexpr S op(const S& a, const S& b) { return a ^ b; }
static constexpr S e() { return S(0); }
};
/**
* @brief 論理積
*/
template <typename T>
struct And {
using S = T;
static constexpr S op(const S& a, const S& b) { return a & b; }
static constexpr S e() { return ~S(0); }
};
/**
* @brief 論理和
*/
template <typename T>
struct Or {
using S = T;
static constexpr S op(const S& a, const S& b) { return a | b; }
static constexpr S e() { return S(0); }
};
/**
* @brief 最大公約数 単位元は0
*/
template <typename T>
struct Gcd {
static_assert(std::is_integral_v<T>);
using S = T;
static constexpr S op(const S& a, const S& b) { return std::gcd(a, b); }
static constexpr S e() { return S(0); }
};
/**
* @brief 最小公倍数 単位元は1
*/
template <typename T>
struct Lcm {
static_assert(std::is_integral_v<T>);
using S = T;
static constexpr S op(const S& a, const S& b) { return std::lcm(a, b); }
static constexpr S e() { return S(1); }
};
/**
* @brief {0, 1, ..., N-1} から自分自身への写像の合成 (変換モノイド)
*
* 要素 f は f[x] が x の行き先を表す std::array<int, N>。全単射でなくてよい
* op(f, g) = f∘g (g を先に適用する)。区間 [l, r) の積は f_l(...f_{r-1}(x)) を表す
* 左から順に適用したい場合は monoid::Reverse<monoid::Mapping<N>> を使う
* 例: SegTree<monoid::Mapping<3>> seg(n); seg.set(i, {0, 2, 1});
* swap(i, j) で i と j を入れ替える写像を作れる
*
* @tparam N 写像の定義域・値域の大きさ
*/
template <std::size_t N>
struct Mapping {
using S = std::array<int, N>;
static constexpr S op(const S& f, const S& g) {
S h{};
for (std::size_t x = 0; x < N; x++) h[x] = f[g[x]];
return h;
}
static constexpr S e() {
S h{};
for (std::size_t x = 0; x < N; x++) h[x] = static_cast<int>(x);
return h;
}
// i と j を入れ替え、ほかは動かさない写像 (互換)
static constexpr S swap(long long i, long long j) {
S h = e();
h[i] = static_cast<int>(j);
h[j] = static_cast<int>(i);
return h;
}
};
/**
* @brief 1次関数 (Affine) の合成
* op(f, g) = f∘g (g を先に適用する)
* 区間 [l, r) の積は f_l(...f_{r-1}(x)) を表す
* 左から順に適用したい (f_{r-1}(...f_l(x)) を求めたい) 場合は monoid::Reverse<monoid::Composite<T>> を使う
*/
template <typename T>
struct Composite {
using S = Affine<T>;
static constexpr S op(const S& f, const S& g) { return {f.a * g.a, f.a * g.b + f.b}; }
static constexpr S e() { return {T(1), T(0)}; }
};
/**
* @brief clamp する関数 (Clamp) の合成
* op(f, g) = f∘g (g を先に適用する)
* clamp(clamp(x, a, b), c, d) = clamp(x, clamp(a, c, d), clamp(b, c, d)) なので、合成も Clamp になる
*/
template <typename T>
struct ClampComposite {
using S = Clamp<T>;
static constexpr S op(const S& f, const S& g) { return {f(g.lb), f(g.ub)}; }
static constexpr S e() { return {}; }
};
/**
* @brief 足してから clamp する関数 (ClampAdd) の合成
* op(f, g) = f∘g (g を先に適用する)
* f(g(x)) = clamp(x + g.add + f.add, f(g.lb), f(g.ub)) なので、合成も ClampAdd になる
* 型の最小値・最大値の lb・ub は下限・上限なしとして扱い、足してもあふれないようにする
*/
template <typename T>
struct ClampAddComposite {
using S = ClampAdd<T>;
static constexpr S op(const S& f, const S& g) {
T lb = g.lb == std::numeric_limits<T>::lowest() ? f.lb : f(g.lb);
T ub = g.ub == std::numeric_limits<T>::max() ? f.ub : f(g.ub);
return {lb, ub, g.add + f.add};
}
static constexpr S e() { return {}; }
};
/**
* @brief 括弧列 対応の取れていない ')' と '(' の個数
*/
struct Parenthesis {
struct S {
long long close; // 対応の取れていない ')' の個数
long long open; // 対応の取れていない '(' の個数
constexpr S(char c = 0) : close(c == ')'), open(c == '(') {}
constexpr S(long long close, long long open) : close(close), open(open) {}
/**
* @brief 正しい括弧列か
*/
constexpr bool is_valid() const { return close == 0 && open == 0; }
};
static constexpr S op(const S& a, const S& b) {
if (a.open >= b.close) return S(a.close, a.open - b.close + b.open);
return S(a.close + b.close - a.open, b.open);
}
static constexpr S e() { return S(); }
};
/**
* @brief 最小値とその位置 同じ値なら左側を優先
* U が整数型なら単位元 (空区間) の位置は -1 で、値が型の最大値の要素があっても単位元として働く
* U が整数型でなければ単位元は {型の最大値, U{}} で、値が型の最大値の要素はないこと
*
* @tparam T 値の型
* @tparam U 位置などの付随する値の型 (整数型なら -1 は使わないこと)
*/
template <typename T, typename U = long long>
struct MinWith {
using S = std::pair<T, U>;
static constexpr S op(const S& a, const S& b) {
if (internal_monoid::with_is_e(a.second)) return b;
if (internal_monoid::with_is_e(b.second)) return a;
return b.first < a.first ? b : a;
}
static constexpr S e() { return {std::numeric_limits<T>::max(), internal_monoid::with_e_position<U>()}; }
};
/**
* @brief 最大値とその位置 同じ値なら左側を優先
* U が整数型なら単位元 (空区間) の位置は -1 で、値が型の最小値の要素があっても単位元として働く
* U が整数型でなければ単位元は {型の最小値, U{}} で、値が型の最小値の要素はないこと
*
* @tparam T 値の型
* @tparam U 位置などの付随する値の型 (整数型なら -1 は使わないこと)
*/
template <typename T, typename U = long long>
struct MaxWith {
using S = std::pair<T, U>;
static constexpr S op(const S& a, const S& b) {
if (internal_monoid::with_is_e(a.second)) return b;
if (internal_monoid::with_is_e(b.second)) return a;
return a.first < b.first ? b : a;
}
static constexpr S e() { return {std::numeric_limits<T>::lowest(), internal_monoid::with_e_position<U>()}; }
};
/**
* @brief 最小値とその個数
*
* @tparam T 値の型
* @tparam U 個数の型
*/
template <typename T, typename U = long long>
struct MinCount {
using S = std::pair<T, U>;
static constexpr S op(const S& a, const S& b) {
if (a.first < b.first) return a;
if (b.first < a.first) return b;
return {a.first, a.second + b.second};
}
static constexpr S e() { return {std::numeric_limits<T>::max(), U(0)}; }
};
/**
* @brief 最大値とその個数
*
* @tparam T 値の型
* @tparam U 個数の型
*/
template <typename T, typename U = long long>
struct MaxCount {
using S = std::pair<T, U>;
static constexpr S op(const S& a, const S& b) {
if (a.first < b.first) return b;
if (b.first < a.first) return a;
return {a.first, a.second + b.second};
}
static constexpr S e() { return {std::numeric_limits<T>::lowest(), U(0)}; }
};
/**
* @brief 区間の和と、空を含む prefix の和の最大値
* S(x) で値 x の1要素を表す要素を作る。単位元は空の区間 {0, 0}
*/
template <typename T>
struct PrefixSumMax {
struct S {
T sum; // 区間の和
T max; // 空を含む prefix の和の最大値 (0 以上)
constexpr S() : sum(0), max(0) {}
constexpr S(const T& x) : sum(x), max(x < T(0) ? T(0) : x) {}
constexpr S(const T& sum, const T& max) : sum(sum), max(max) {}
friend constexpr bool operator==(const S& a, const S& b) { return a.sum == b.sum && a.max == b.max; }
friend constexpr bool operator!=(const S& a, const S& b) { return !(a == b); }
};
static constexpr S op(const S& a, const S& b) { return S(a.sum + b.sum, std::max(a.max, a.sum + b.max)); }
static constexpr S e() { return S(); }
};
/**
* @brief 区間の和と、空を含む prefix の和の最小値
* S(x) で値 x の1要素を表す要素を作る。単位元は空の区間 {0, 0}
*/
template <typename T>
struct PrefixSumMin {
struct S {
T sum; // 区間の和
T min; // 空を含む prefix の和の最小値 (0 以下)
constexpr S() : sum(0), min(0) {}
constexpr S(const T& x) : sum(x), min(T(0) < x ? T(0) : x) {}
constexpr S(const T& sum, const T& min) : sum(sum), min(min) {}
friend constexpr bool operator==(const S& a, const S& b) { return a.sum == b.sum && a.min == b.min; }
friend constexpr bool operator!=(const S& a, const S& b) { return !(a == b); }
};
static constexpr S op(const S& a, const S& b) { return S(a.sum + b.sum, std::min(a.min, a.sum + b.min)); }
static constexpr S e() { return S(); }
};
/**
* @brief 区間の和と、空を含む prefix の和の最小値・最大値
* S(x) で値 x の1要素を表す要素を作る。単位元は空の区間 {0, 0, 0}
*/
template <typename T = long long>
struct PrefixSumMinMax {
struct S {
T sum; // 区間の和
T min; // 空を含む prefix の和の最小値 (0 以下)
T max; // 空を含む prefix の和の最大値 (0 以上)
constexpr S() : sum(0), min(0), max(0) {}
constexpr S(const T& x) : sum(x), min(T(0) < x ? T(0) : x), max(x < T(0) ? T(0) : x) {}
constexpr S(const T& sum, const T& min, const T& max) : sum(sum), min(min), max(max) {}
friend constexpr bool operator==(const S& a, const S& b) { return a.sum == b.sum && a.min == b.min && a.max == b.max; }
friend constexpr bool operator!=(const S& a, const S& b) { return !(a == b); }
};
static constexpr S op(const S& a, const S& b) {
return S(a.sum + b.sum, std::min(a.min, a.sum + b.min), std::max(a.max, a.sum + b.max));
}
static constexpr S e() { return S(); }
};
/**
* @brief 区間の和と、空を含む suffix の和の最大値
* S(x) で値 x の1要素を表す要素を作る。単位元は空の区間 {0, 0}
*/
template <typename T>
struct SuffixSumMax {
struct S {
T sum; // 区間の和
T max; // 空を含む suffix の和の最大値 (0 以上)
constexpr S() : sum(0), max(0) {}
constexpr S(const T& x) : sum(x), max(x < T(0) ? T(0) : x) {}
constexpr S(const T& sum, const T& max) : sum(sum), max(max) {}
friend constexpr bool operator==(const S& a, const S& b) { return a.sum == b.sum && a.max == b.max; }
friend constexpr bool operator!=(const S& a, const S& b) { return !(a == b); }
};
static constexpr S op(const S& a, const S& b) { return S(a.sum + b.sum, std::max(b.max, a.max + b.sum)); }
static constexpr S e() { return S(); }
};
/**
* @brief 区間の和と、空を含む suffix の和の最小値
* S(x) で値 x の1要素を表す要素を作る。単位元は空の区間 {0, 0}
*/
template <typename T>
struct SuffixSumMin {
struct S {
T sum; // 区間の和
T min; // 空を含む suffix の和の最小値 (0 以下)
constexpr S() : sum(0), min(0) {}
constexpr S(const T& x) : sum(x), min(T(0) < x ? T(0) : x) {}
constexpr S(const T& sum, const T& min) : sum(sum), min(min) {}
friend constexpr bool operator==(const S& a, const S& b) { return a.sum == b.sum && a.min == b.min; }
friend constexpr bool operator!=(const S& a, const S& b) { return !(a == b); }
};
static constexpr S op(const S& a, const S& b) { return S(a.sum + b.sum, std::min(b.min, a.min + b.sum)); }
static constexpr S e() { return S(); }
};
/**
* @brief 区間の和、空を含む prefix・suffix の和の最大値、空を含む部分配列の和の最大値
* S(x) で値 x の1要素を表す要素を作る。単位元は空の区間 {0, 0, 0, 0}
* 静的な列に対して一度だけ求めるなら dp/maximum-subarray.hpp の maximum_subarray
*/
template <typename T>
struct MaxSubarraySum {
struct S {
T sum; // 区間の和
T prefix; // 空を含む prefix の和の最大値 (0 以上)
T suffix; // 空を含む suffix の和の最大値 (0 以上)
T best; // 空を含む部分配列の和の最大値 (0 以上)
constexpr S() : sum(0), prefix(0), suffix(0), best(0) {}
constexpr S(const T& x) : sum(x), prefix(x < T(0) ? T(0) : x), suffix(prefix), best(prefix) {}
constexpr S(const T& sum, const T& prefix, const T& suffix, const T& best)
: sum(sum), prefix(prefix), suffix(suffix), best(best) {}
friend constexpr bool operator==(const S& a, const S& b) {
return a.sum == b.sum && a.prefix == b.prefix && a.suffix == b.suffix && a.best == b.best;
}
friend constexpr bool operator!=(const S& a, const S& b) { return !(a == b); }
};
static constexpr S op(const S& a, const S& b) {
return S(a.sum + b.sum, std::max(a.prefix, a.sum + b.prefix), std::max(b.suffix, a.suffix + b.sum),
std::max({a.best, b.best, a.suffix + b.prefix}));
}
static constexpr S e() { return S(); }
};
/**
* @brief 積の順序を逆にしたモノイド op(a, b) = M::op(b, a)
*
* 例: SegTree<monoid::Reverse<monoid::Composite<mint>>> seg(v); の区間 [l, r) の積は f_{r-1}(...f_l(x))
*
* @tparam M もとのモノイド
*/
template <typename M>
struct Reverse {
using S = typename M::S;
M m;
constexpr Reverse() : m() {}
constexpr explicit Reverse(M m) : m(std::move(m)) {}
constexpr S op(const S& a, const S& b) const { return m.op(b, a); }
constexpr S e() const { return m.e(); }
};
} // namespace monoid
/**
* @brief 関数オブジェクトと単位元から実行時に作るモノイド
* ラムダ式を使える
*
* 例: SegTree seg(v, Monoid([](int a, int b) { return std::max(a, b); }, -1));
*
* @tparam T 要素の型
* @tparam Op 積の関数オブジェクトの型
*/
template <typename T, typename Op>
struct Monoid {
using S = T;
Op op_object;
S identity;
Monoid() = default;
constexpr Monoid(Op op, const S& e) : op_object(std::move(op)), identity(e) {}
constexpr S op(const S& a, const S& b) const { return op_object(a, b); }
constexpr S e() const { return identity; }
};
template <typename Op, typename T>
Monoid(Op, T) -> Monoid<T, Op>;
#line 7 "test/unittest/algebra/monoid.test.cpp"
#line 9 "test/unittest/algebra/monoid.test.cpp"
#include <deque>
#include <forward_list>
#include <iostream>
#line 13 "test/unittest/algebra/monoid.test.cpp"
#include <list>
#include <random>
#include <sstream>
#include <string>
#line 19 "test/unittest/algebra/monoid.test.cpp"
#include <vector>
#line 2 "src/algebra/group.hpp"
/**
* @file group.hpp
* @brief 群の定義
*
* 群はモノイド (algebra/monoid.hpp) のメンバに加えて次のメンバを持つ型として表す
* - S inv(const S& a): 逆元
*/
#line 14 "src/algebra/group.hpp"
#line 16 "src/algebra/group.hpp"
namespace group {
/**
* @brief 加法群
*/
template <typename T>
struct Sum : monoid::Sum<T> {
using S = T;
static constexpr S inv(const S& a) { return -a; }
};
/**
* @brief 乗法群 (0を含まない体の元など)
*/
template <typename T>
struct Prod : monoid::Prod<T> {
using S = T;
static constexpr S inv(const S& a) { return S(1) / a; }
};
/**
* @brief 排他的論理和
*/
template <typename T>
struct Xor : monoid::Xor<T> {
using S = T;
static constexpr S inv(const S& a) { return a; }
};
/**
* @brief {0, 1, ..., N-1} の置換 (全単射) の合成
*
* monoid::Mapping<N> に逆置換を加えたもの。要素は置換であること
* op(f, g) = f∘g (g を先に適用する)
*
* @tparam N 置換する要素の個数
*/
template <std::size_t N>
struct Permutation : monoid::Mapping<N> {
using S = std::array<int, N>;
static constexpr S inv(const S& f) {
S h{};
for (std::size_t x = 0; x < N; x++) h[f[x]] = static_cast<int>(x);
return h;
}
};
} // namespace group
/**
* @brief 関数オブジェクトと単位元から実行時に作る群
* ラムダ式を使える
*
* @tparam T 要素の型
* @tparam Op 積の関数オブジェクトの型
* @tparam Inv 逆元の関数オブジェクトの型
*/
template <typename T, typename Op, typename Inv>
struct Group {
using S = T;
Op op_object;
S identity;
Inv inv_object;
Group() = default;
constexpr Group(Op op, const S& e, Inv inv) : op_object(std::move(op)), identity(e), inv_object(std::move(inv)) {}
constexpr S op(const S& a, const S& b) const { return op_object(a, b); }
constexpr S e() const { return identity; }
constexpr S inv(const S& a) const { return inv_object(a); }
};
template <typename Op, typename T, typename Inv>
Group(Op, T, Inv) -> Group<T, Op, Inv>;
#line 2 "src/data_structures/dual-segtree.hpp"
/**
* @file dual-segtree.hpp
* @brief 双対セグメント木 (区間作用、1点取得)
*/
#include <cassert>
#include <initializer_list>
#line 13 "src/data_structures/dual-segtree.hpp"
#line 2 "src/algebra/acted-monoid.hpp"
/**
* @file acted-monoid.hpp
* @brief 作用素付きモノイドの定義
*
* 作用素付きモノイドはモノイド (algebra/monoid.hpp) のメンバに加えて次のメンバを持つ型として表す
* - using F: 作用素の型
* - S mapping(const F& f, const S& x): 作用素の適用 f(x)
* 区間の情報が必要な場合は mapping(f, x, sz) (sz は区間の長さ) や mapping(f, x, l, r) (区間 [l, r)) でもよい
* sz, l, r は long long で渡す (動的セグメント木では int に収まらないことがある)
* - F composition(const F& f, const F& g): 作用素の合成 f∘g (gを適用した後にfを適用する)
* - F id(): 恒等写像
* 作用素が群をなす場合 (imos.hpp で使う) は
* - F inv(const F& f): 逆作用素
*/
#line 27 "src/algebra/acted-monoid.hpp"
#line 29 "src/algebra/acted-monoid.hpp"
#if __cplusplus < 202002L
namespace internal_acted_monoid {
template <typename A, typename = void>
struct has_mapping_lr : std::false_type {};
template <typename A>
struct has_mapping_lr<A, std::void_t<decltype(std::declval<const A&>().mapping(std::declval<const typename A::F&>(), std::declval<const typename A::S&>(), 0, 0))>> : std::true_type {};
template <typename A, typename = void>
struct has_mapping_sz : std::false_type {};
template <typename A>
struct has_mapping_sz<A, std::void_t<decltype(std::declval<const A&>().mapping(std::declval<const typename A::F&>(), std::declval<const typename A::S&>(), 0))>> : std::true_type {};
} // namespace internal_acted_monoid
#endif
namespace acted_monoid {
/**
* @brief 区間 [l, r) を表す要素に作用素を適用する
* mapping の引数の形の違いを吸収する
*/
template <typename A>
constexpr auto apply_mapping(const A& a, const typename A::F& f, const typename A::S& x, long long l, long long r) {
#if __cplusplus >= 202002L
if constexpr (requires { a.mapping(f, x, l, r); }) {
#else
if constexpr (internal_acted_monoid::has_mapping_lr<A>::value) {
#endif
return a.mapping(f, x, l, r);
#if __cplusplus >= 202002L
} else if constexpr (requires { a.mapping(f, x, r - l); }) {
#else
} else if constexpr (internal_acted_monoid::has_mapping_sz<A>::value) {
#endif
return a.mapping(f, x, r - l);
} else {
return a.mapping(f, x);
}
}
/**
* @brief 区間加算、区間和
*/
template <typename T>
struct AddSum : monoid::Sum<T> {
using S = T;
using F = T;
static constexpr S mapping(const F& f, const S& x, long long sz) { return x + f * S(sz); }
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
static constexpr F inv(const F& f) { return -f; }
};
/**
* @brief 区間の位置 i に constant + slope * i を加算、区間和
* arithmetic_progression(l, first, step) で左端 l の初項 first、公差 step を指定する
*/
template <typename T = long long>
struct LinearAddSum : monoid::Sum<T> {
using S = T;
struct F {
T constant = T(0), slope = T(0);
};
static constexpr F arithmetic_progression(long long l, const T& first, const T& step) {
assert(l >= 0);
return {first - step * T(l), step};
}
static constexpr S mapping(const F& f, const S& x, long long l, long long r) {
assert(0 <= l && l <= r);
const long long n = r - l;
if (n == 0) return x;
// sum i = l*n + n*(n-1)/2。整数側で 2 で割り、和・積は T で計算する。
const T offset = n % 2 == 0 ? T(n / 2) * T(n - 1) : T(n) * T((n - 1) / 2);
return x + f.constant * T(n) + f.slope * (T(l) * T(n) + offset);
}
static constexpr F composition(const F& f, const F& g) { return {f.constant + g.constant, f.slope + g.slope}; }
static constexpr F id() { return F(); }
static constexpr F inv(const F& f) { return {-f.constant, -f.slope}; }
};
/**
* @brief 区間乗算、区間和
*/
template <typename T>
struct MulSum : monoid::Sum<T> {
using S = T;
using F = T;
static constexpr S mapping(const F& f, const S& x) { return f * x; }
static constexpr F composition(const F& f, const F& g) { return f * g; }
static constexpr F id() { return F(1); }
static constexpr F inv(const F& f) { return F(1) / f; }
};
/**
* @brief 区間加算、区間最小値
*/
template <typename T>
struct AddMin : monoid::Min<T> {
using S = T;
using F = T;
static constexpr S mapping(const F& f, const S& x) { return x + f; }
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
};
/**
* @brief 区間加算、区間最大値
*/
template <typename T>
struct AddMax : monoid::Max<T> {
using S = T;
using F = T;
static constexpr S mapping(const F& f, const S& x) { return x + f; }
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
};
/**
* @brief 区間代入、区間和
*/
template <typename T>
struct UpdateSum : monoid::Sum<T> {
using S = T;
using F = std::optional<T>;
static constexpr S mapping(const F& f, const S& x, long long sz) { return f ? *f * S(sz) : x; }
static constexpr F composition(const F& f, const F& g) { return f ? f : g; }
static constexpr F id() { return std::nullopt; }
};
/**
* @brief 区間代入、区間最小値
*/
template <typename T>
struct UpdateMin : monoid::Min<T> {
using S = T;
using F = std::optional<T>;
static constexpr S mapping(const F& f, const S& x) { return f ? *f : x; }
static constexpr F composition(const F& f, const F& g) { return f ? f : g; }
static constexpr F id() { return std::nullopt; }
};
/**
* @brief 区間代入、区間最大値
*/
template <typename T>
struct UpdateMax : monoid::Max<T> {
using S = T;
using F = std::optional<T>;
static constexpr S mapping(const F& f, const S& x) { return f ? *f : x; }
static constexpr F composition(const F& f, const F& g) { return f ? f : g; }
static constexpr F id() { return std::nullopt; }
};
/**
* @brief 区間chmin、区間最小値
*/
template <typename T>
struct ChminMin : monoid::Min<T> {
using S = T;
using F = T;
static constexpr S mapping(const F& f, const S& x) { return std::min(f, x); }
static constexpr F composition(const F& f, const F& g) { return std::min(f, g); }
static constexpr F id() { return std::numeric_limits<F>::max(); }
};
/**
* @brief 区間chmax、区間最大値
*/
template <typename T>
struct ChmaxMax : monoid::Max<T> {
using S = T;
using F = T;
static constexpr S mapping(const F& f, const S& x) { return std::max(f, x); }
static constexpr F composition(const F& f, const F& g) { return std::max(f, g); }
static constexpr F id() { return std::numeric_limits<F>::lowest(); }
};
/**
* @brief 区間 clamp x <- min(max(x, lb), ub) (Clamp)、区間最小値
* clamp は単調非減少なので、最小値に適用すればよい
*/
template <typename T>
struct ClampMin : monoid::Min<T> {
using S = T;
using F = Clamp<T>;
static constexpr S mapping(const F& f, const S& x) { return f(x); }
static constexpr F composition(const F& f, const F& g) { return monoid::ClampComposite<T>::op(f, g); }
static constexpr F id() { return {}; }
};
/**
* @brief 区間 clamp x <- min(max(x, lb), ub) (Clamp)、区間最大値
*/
template <typename T>
struct ClampMax : monoid::Max<T> {
using S = T;
using F = Clamp<T>;
static constexpr S mapping(const F& f, const S& x) { return f(x); }
static constexpr F composition(const F& f, const F& g) { return monoid::ClampComposite<T>::op(f, g); }
static constexpr F id() { return {}; }
};
/**
* @brief 区間 clamp x <- min(max(x, lb), ub) (Clamp)、区間最小値と最大値の組 {min, max} (monoid::MinMax)
*/
template <typename T>
struct ClampMinMax : monoid::MinMax<T> {
using S = typename monoid::MinMax<T>::S;
using F = Clamp<T>;
static constexpr S mapping(const F& f, const S& x) {
if (x.min > x.max) return x;
return {f(x.min), f(x.max)};
}
static constexpr F composition(const F& f, const F& g) { return monoid::ClampComposite<T>::op(f, g); }
static constexpr F id() { return {}; }
};
/**
* @brief 区間 加算と clamp x <- min(max(x + add, lb), ub) (ClampAdd)、区間最小値
* 区間加算・chmin・chmax・代入をまとめて扱える。単調非減少なので、最小値に適用すればよい
*/
template <typename T>
struct ClampAddMin : monoid::Min<T> {
using S = T;
using F = ClampAdd<T>;
static constexpr S mapping(const F& f, const S& x) { return f(x); }
static constexpr F composition(const F& f, const F& g) { return monoid::ClampAddComposite<T>::op(f, g); }
static constexpr F id() { return {}; }
};
/**
* @brief 区間 加算と clamp x <- min(max(x + add, lb), ub) (ClampAdd)、区間最大値
*/
template <typename T>
struct ClampAddMax : monoid::Max<T> {
using S = T;
using F = ClampAdd<T>;
static constexpr S mapping(const F& f, const S& x) { return f(x); }
static constexpr F composition(const F& f, const F& g) { return monoid::ClampAddComposite<T>::op(f, g); }
static constexpr F id() { return {}; }
};
/**
* @brief 区間 加算と clamp x <- min(max(x + add, lb), ub) (ClampAdd)、区間最小値と最大値の組 {min, max} (monoid::MinMax)
*/
template <typename T>
struct ClampAddMinMax : monoid::MinMax<T> {
using S = typename monoid::MinMax<T>::S;
using F = ClampAdd<T>;
static constexpr S mapping(const F& f, const S& x) {
if (x.min > x.max) return x;
return {f(x.min), f(x.max)};
}
static constexpr F composition(const F& f, const F& g) { return monoid::ClampAddComposite<T>::op(f, g); }
static constexpr F id() { return {}; }
};
/**
* @brief 区間アフィン変換 x <- a * x + b (Affine)、区間和
*/
template <typename T>
struct AffineSum : monoid::Sum<T> {
using S = T;
using F = Affine<T>;
static constexpr S mapping(const F& f, const S& x, long long sz) { return f.a * x + f.b * S(sz); }
static constexpr F composition(const F& f, const F& g) { return {f.a * g.a, f.a * g.b + f.b}; }
static constexpr F id() { return {T(1), T(0)}; }
};
/**
* @brief 区間代入、1次関数の合成 (monoid::Composite)
*/
template <typename T>
struct UpdateComposite : monoid::Composite<T> {
using S = Affine<T>;
using F = std::optional<S>;
static constexpr S mapping(const F& f, const S& x, long long sz) {
if (!f) return x;
// f を sz 回合成する
S ret = monoid::Composite<T>::e(), p = *f;
for (; sz > 0; sz >>= 1) {
if (sz & 1) ret = monoid::Composite<T>::op(ret, p);
p = monoid::Composite<T>::op(p, p);
}
return ret;
}
static constexpr F composition(const F& f, const F& g) { return f ? f : g; }
static constexpr F id() { return std::nullopt; }
};
/**
* @brief 区間加算、区間最小値とその位置 (monoid::MinWith)
*/
template <typename T, typename U = long long>
struct AddMinWith : monoid::MinWith<T, U> {
using S = std::pair<T, U>;
using F = T;
// 単位元 (位置が -1) は単位元のまま (型の最大値・最小値に足してあふれないように)
static constexpr S mapping(const F& f, const S& x) {
if (internal_monoid::with_is_e(x.second)) return x;
return {x.first + f, x.second};
}
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
};
/**
* @brief 区間加算、区間最大値とその位置 (monoid::MaxWith)
*/
template <typename T, typename U = long long>
struct AddMaxWith : monoid::MaxWith<T, U> {
using S = std::pair<T, U>;
using F = T;
// 単位元 (位置が -1) は単位元のまま (型の最大値・最小値に足してあふれないように)
static constexpr S mapping(const F& f, const S& x) {
if (internal_monoid::with_is_e(x.second)) return x;
return {x.first + f, x.second};
}
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
};
/**
* @brief 区間加算、区間最小値とその個数 (monoid::MinCount)
*/
template <typename T, typename U = long long>
struct AddMinCount : monoid::MinCount<T, U> {
using S = std::pair<T, U>;
using F = T;
static constexpr S mapping(const F& f, const S& x) { return {x.first + f, x.second}; }
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
};
/**
* @brief 区間加算、区間最大値とその個数 (monoid::MaxCount)
*/
template <typename T, typename U = long long>
struct AddMaxCount : monoid::MaxCount<T, U> {
using S = std::pair<T, U>;
using F = T;
static constexpr S mapping(const F& f, const S& x) { return {x.first + f, x.second}; }
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
};
/**
* @brief 区間加算、区間の0乗和からK乗和
*
* S(x) で値 x の1要素を表す要素を作る。S::operator[](i) で i 乗和を取得する
*/
template <typename T, int K>
struct AddPowerSum {
struct S {
std::array<T, K + 1> val;
constexpr S() : val{} {}
constexpr S(const T& x) : val{} {
val[0] = T(1);
for (int i = 1; i <= K; i++) val[i] = val[i - 1] * x;
}
constexpr const T& operator[](long long i) const { return val[i]; }
};
using F = T;
static constexpr S op(const S& a, const S& b) {
S ret;
for (int i = 0; i <= K; i++) ret.val[i] = a.val[i] + b.val[i];
return ret;
}
static constexpr S e() { return S(); }
static S mapping(const F& f, const S& x) {
// sum (x+f)^i = sum_j binom(i, j) f^j x^(i-j)
static const auto binom = [] {
std::array<std::array<T, K + 1>, K + 1> c{};
for (int i = 0; i <= K; i++) {
c[i][0] = c[i][i] = T(1);
for (int j = 1; j < i; j++) c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
return c;
}();
std::array<T, K + 1> pw{};
pw[0] = T(1);
for (int i = 1; i <= K; i++) pw[i] = pw[i - 1] * f;
S ret;
for (int i = 0; i <= K; i++) {
for (int j = 0; j <= i; j++) ret.val[i] += binom[i][j] * pw[j] * x.val[i - j];
}
return ret;
}
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return F(0); }
};
/** @brief 区間アフィン変換、区間最小値・最大値 (負の倍率も許す) */
template <typename T = long long>
struct AffineMinMax : monoid::MinMax<T> {
using S = typename monoid::MinMax<T>::S;
using F = Affine<T>;
static constexpr S mapping(const F& f, const S& x) {
if (x.min > x.max) return x;
if (f.a < T(0)) return {f(x.max), f(x.min)};
return {f(x.min), f(x.max)};
}
static constexpr F composition(const F& f, const F& g) { return monoid::Composite<T>::op(f, g); }
static constexpr F id() { return F(); }
};
/** @brief 区間アフィン変換、区間の 0 乗和から K 乗和 */
template <typename T = long long, long long K = 2>
struct AffinePowerSum : AddPowerSum<T, K> {
static_assert(K >= 0);
using S = typename AddPowerSum<T, K>::S;
using F = Affine<T>;
static S mapping(const F& f, const S& x) {
std::array<T, K + 1> pa{}, pb{}, binom{};
pa[0] = pb[0] = binom[0] = T(1);
for (long long i = 1; i <= K; ++i) {
pa[i] = pa[i - 1] * f.a;
pb[i] = pb[i - 1] * f.b;
}
S res;
for (long long i = 0; i <= K; ++i) {
for (long long j = 0; j <= i; ++j) res.val[i] += binom[j] * pa[j] * pb[i - j] * x[j];
if (i < K)
for (long long j = i + 1; j >= 1; --j) binom[j] += binom[j - 1];
}
return res;
}
static constexpr F composition(const F& f, const F& g) { return monoid::Composite<T>::op(f, g); }
static constexpr F id() { return F(); }
};
/** @brief 区間加算、区間 gcd。S::val() で gcd を取得する */
template <typename T = long long>
struct AddGcd {
static_assert(std::is_integral_v<T> && std::is_signed_v<T>);
struct S {
T first = T(0), last = T(0), differences_gcd = T(0);
long long size = 0;
constexpr S() = default;
constexpr S(const T& x) : first(x), last(x), size(1) {}
constexpr T val() const { return std::gcd(first, differences_gcd); }
};
using F = T;
static constexpr S op(const S& a, const S& b) {
if (a.size == 0) return b;
if (b.size == 0) return a;
S res;
res.first = a.first;
res.last = b.last;
res.differences_gcd = std::gcd(std::gcd(a.differences_gcd, b.differences_gcd), b.first - a.last);
res.size = a.size + b.size;
return res;
}
static constexpr S e() { return S(); }
static constexpr S mapping(const F& f, const S& x) {
S res = x;
if (res.size != 0) {
res.first += f;
res.last += f;
}
return res;
}
static constexpr F composition(const F& f, const F& g) { return f + g; }
static constexpr F id() { return T(0); }
static constexpr F inv(const F& f) { return -f; }
};
/** @brief 2 列への区間加算、各列の和と要素ごとの積の和 */
template <typename T = long long>
struct AddProductSum {
struct S {
T sum_a = T(0), sum_b = T(0), product_sum = T(0);
constexpr S() = default;
constexpr S(const T& a, const T& b) : sum_a(a), sum_b(b), product_sum(a * b) {}
constexpr S(const std::array<T, 2>& x) : S(x[0], x[1]) {}
};
using F = std::array<T, 2>;
static constexpr S op(const S& a, const S& b) {
S res;
res.sum_a = a.sum_a + b.sum_a;
res.sum_b = a.sum_b + b.sum_b;
res.product_sum = a.product_sum + b.product_sum;
return res;
}
static constexpr S e() { return S(); }
static constexpr S mapping(const F& f, const S& x, long long sz) {
S res;
res.sum_a = x.sum_a + f[0] * T(sz);
res.sum_b = x.sum_b + f[1] * T(sz);
res.product_sum = x.product_sum + f[0] * x.sum_b + f[1] * x.sum_a + f[0] * f[1] * T(sz);
return res;
}
static constexpr F composition(const F& f, const F& g) { return {f[0] + g[0], f[1] + g[1]}; }
static constexpr F id() { return {T(0), T(0)}; }
static constexpr F inv(const F& f) { return {-f[0], -f[1]}; }
};
/**
* @brief 区間の位置 i に f[0] + f[1]*i + ... + f[K]*i^K を加算、区間和
* 整数の因子を約分して二項係数を求めるので、偶数の法の modint でも使える
*/
template <typename T = long long, long long K = 2>
struct PolynomialAddSum : monoid::Sum<T> {
static_assert(K >= 0);
using S = T;
using F = std::array<T, K + 1>;
private:
// [0, n) の添字の 0 乗和から K 乗和。整数の大きな積や T での除算は使わない。
static std::array<T, K + 1> index_power_sums(long long n, long long degree) {
assert(0 <= degree && degree <= K);
std::array<T, K + 2> binom{};
std::array<long long, K + 1> factors{};
for (long long k = 1; k <= K + 1 && k <= degree + 1 && k <= n; ++k) {
factors[k - 1] = n - k + 1;
long long divisor = k;
for (long long j = 0; j < k && divisor > 1; ++j) {
long long g = std::gcd(factors[j], divisor);
factors[j] /= g;
divisor /= g;
}
assert(divisor == 1);
T value(1);
for (long long j = 0; j < k; ++j) value *= T(factors[j]);
binom[k] = value;
}
// i^k = sum_j Stirling2(k, j) * j! * C(i, j)
// sum_{i=0}^{n-1} C(i, j) = C(n, j+1)
std::array<T, K + 1> stirling{}, factorial{}, sums{};
stirling[0] = factorial[0] = T(1);
for (long long j = 1; j <= K && j <= degree; ++j) factorial[j] = factorial[j - 1] * T(j);
for (long long k = 0; k <= K && k <= degree; ++k) {
for (long long j = 0; j <= k; ++j) sums[k] += stirling[j] * factorial[j] * binom[j + 1];
if (k < K && k < degree) {
for (long long j = k + 1; j >= 1; --j) stirling[j] = T(j) * stirling[j] + stirling[j - 1];
stirling[0] = T(0);
}
}
return sums;
}
public:
static S mapping(const F& f, const S& x, long long l, long long r) {
assert(0 <= l && l <= r);
if (l == r) return x;
long long degree = K;
while (degree >= 0 && f[degree] == T(0)) --degree;
if (degree < 0) return x;
auto left = index_power_sums(l, degree), right = index_power_sums(r, degree);
S res = x;
for (long long k = 0; k <= degree; ++k) res += f[k] * (right[k] - left[k]);
return res;
}
static constexpr F composition(const F& f, const F& g) {
F res{};
for (long long k = 0; k <= K; ++k) res[k] = f[k] + g[k];
return res;
}
static constexpr F id() { return F{}; }
static constexpr F inv(const F& f) {
F res{};
for (long long k = 0; k <= K; ++k) res[k] = -f[k];
return res;
}
};
/**
* @brief 成分の並べ替え (monoid::Mapping)、モノイド M の N 個の直積
*
* 要素は M の要素を N 個並べた std::array で、積は成分ごとに M::op をとる
* 作用素 f は monoid::Mapping<N> の要素で、mapping(f, x)[i] = x[f[i]] (成分 i に x の成分 f[i] を持ってくる)
* f は全単射でなくてよい。例えば N = 3 で f = {1, 1, 2} は成分 0 を成分 1 で上書きする
* 積が成分ごとなので、M によらず作用は積と可換になる
*
* @tparam M static な op, e を持つモノイド
* @tparam N 成分の個数
*/
template <typename M, std::size_t N>
struct Rearrange {
using S = std::array<typename M::S, N>;
using F = typename monoid::Mapping<N>::S;
static constexpr S op(const S& a, const S& b) {
S res{};
for (std::size_t i = 0; i < N; i++) res[i] = M::op(a[i], b[i]);
return res;
}
static constexpr S e() {
S res{};
for (std::size_t i = 0; i < N; i++) res[i] = M::e();
return res;
}
static constexpr S mapping(const F& f, const S& x) {
S res{};
for (std::size_t i = 0; i < N; i++) res[i] = x[f[i]];
return res;
}
// mapping(f, mapping(g, x))[i] = x[g[f[i]]] なので、Mapping の積としては g∘f になる
static constexpr F composition(const F& f, const F& g) { return monoid::Mapping<N>::op(g, f); }
static constexpr F id() { return monoid::Mapping<N>::e(); }
// 成分 i と j を入れ替える作用素
static constexpr F swap(long long i, long long j) { return monoid::Mapping<N>::swap(i, j); }
};
} // namespace acted_monoid
/**
* @brief 関数オブジェクトから実行時に作る作用素付きモノイド
* ラムダ式を使える
*
* @tparam T 要素の型
* @tparam Op 積の関数オブジェクトの型
* @tparam U 作用素の型
* @tparam Mapping 作用素を適用する関数オブジェクトの型 引数は (f, x), (f, x, sz), (f, x, l, r) のいずれか
* @tparam Composition 作用素の合成の関数オブジェクトの型
*/
template <typename T, typename Op, typename U, typename Mapping, typename Composition>
struct ActedMonoid {
using S = T;
using F = U;
Op op_object;
S identity;
Mapping mapping_object;
Composition composition_object;
F lazy_identity;
ActedMonoid() = default;
constexpr ActedMonoid(Op op, const S& e, Mapping mapping, Composition composition, const F& id)
: op_object(std::move(op)), identity(e), mapping_object(std::move(mapping)), composition_object(std::move(composition)), lazy_identity(id) {}
constexpr S op(const S& a, const S& b) const { return op_object(a, b); }
constexpr S e() const { return identity; }
constexpr auto mapping(const F& f, const S& x, long long l, long long r) const {
if constexpr (std::is_invocable_v<const Mapping&, const F&, const S&, long long, long long>) {
return mapping_object(f, x, l, r);
} else if constexpr (std::is_invocable_v<const Mapping&, const F&, const S&, long long>) {
return mapping_object(f, x, r - l);
} else {
return mapping_object(f, x);
}
}
constexpr F composition(const F& f, const F& g) const { return composition_object(f, g); }
constexpr F id() const { return lazy_identity; }
};
template <typename Op, typename T, typename Mapping, typename Composition, typename U>
ActedMonoid(Op, T, Mapping, Composition, U) -> ActedMonoid<T, Op, U, Mapping, Composition>;
#line 2 "src/utility/traits.hpp"
/**
* @file traits.hpp
* @brief 型特性
*/
#line 9 "src/utility/traits.hpp"
#include <functional>
#include <iterator>
#include <set>
#line 14 "src/utility/traits.hpp"
#if __cplusplus >= 202002L
#include <concepts>
#include <ranges>
#endif
namespace internal_traits {
using std::begin, std::end;
#if __cplusplus >= 202002L
template <class T>
struct is_range_impl : std::bool_constant < requires(T& t) {
begin(t);
end(t);
}>{};
#else
template <class T, class = void>
struct is_range_impl : std::false_type {};
template <class T>
struct is_range_impl<T, std::void_t<decltype(begin(std::declval<T&>()), end(std::declval<T&>()))>> : std::true_type {};
#endif
// サイズ付き範囲から要素を直接構築するコンストラクタで共有する。
#if __cplusplus >= 202002L
template <class R, class S>
concept sized_constructible_range = std::ranges::input_range<R> && std::ranges::sized_range<R> &&
std::is_constructible_v<S, std::ranges::range_reference_t<R>>;
template <class R>
auto range_size(R& r) {
return std::ranges::size(r);
}
template <class R>
auto range_begin(R& r) {
return std::ranges::begin(r);
}
template <class R>
using range_value_t = std::ranges::range_value_t<R>;
#else
using std::size;
template <class R>
auto range_size(R& r) -> decltype(size(r)) {
return size(r);
}
template <class R>
auto range_begin(R& r) -> decltype(begin(r)) {
return begin(r);
}
template <class R>
using range_value_t = typename std::iterator_traits<decltype(range_begin(std::declval<R&>()))>::value_type;
template <class R, class S, class = void>
struct is_sized_constructible_range : std::false_type {};
template <class R, class S>
struct is_sized_constructible_range<R, S, std::void_t<decltype(range_size(std::declval<R&>())), decltype(++std::declval<decltype(begin(std::declval<R&>()))&>()), decltype(begin(std::declval<R&>()) != end(std::declval<R&>())), decltype(*begin(std::declval<R&>()))>>
: std::is_constructible<S, decltype(*begin(std::declval<R&>()))> {};
#endif
} // namespace internal_traits
template <class T>
struct is_range : internal_traits::is_range_impl<T>::type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;
#if __cplusplus >= 202002L
#define HAS_METHOD(func_name) \
namespace internal_traits { \
template <class T> \
concept has_##func_name##_impl = requires { std::declval<T>().func_name(); }; \
} \
template <class T> \
struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T>> {}; \
template <class T> \
inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;
#define HAS_METHOD_ARG(func_name) \
namespace internal_traits { \
template <class T, class U> \
concept has_##func_name##_impl = requires { std::declval<T>().func_name(std::declval<U>()); }; \
} \
template <class T, class U> \
struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T, U>> {}; \
template <class T, class U> \
inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#else
#define HAS_METHOD(func_name) \
namespace internal_traits { \
template <class T, class = void> \
struct has_##func_name##_impl : std::false_type {}; \
template <class T> \
struct has_##func_name##_impl<T, std::void_t<decltype(std::declval<T>().func_name())>> \
: std::true_type {}; \
} \
template <class T> \
struct has_##func_name : internal_traits::has_##func_name##_impl<T>::type {}; \
template <class T> \
inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;
#define HAS_METHOD_ARG(func_name) \
namespace internal_traits { \
template <class T, typename U, class = void> \
struct has_##func_name##_impl : std::false_type {}; \
template <class T, typename U> \
struct has_##func_name##_impl<T, U, std::void_t<decltype(std::declval<T>().func_name(std::declval<U>()))>> \
: std::true_type {}; \
} \
template <class T, typename U> \
struct has_##func_name : internal_traits::has_##func_name##_impl<T, U>::type {}; \
template <class T, typename U> \
inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#endif
HAS_METHOD(repr)
HAS_METHOD(type_str)
HAS_METHOD(initializer_str)
HAS_METHOD(max)
HAS_METHOD(min)
HAS_METHOD(reversed)
HAS_METHOD(sorted)
HAS_METHOD(sum)
HAS_METHOD(product)
HAS_METHOD(product_xor)
HAS_METHOD_ARG(count)
HAS_METHOD_ARG(find)
HAS_METHOD_ARG(lower_bound)
HAS_METHOD_ARG(upper_bound)
#define ENABLE_IF_T_IMPL(expr) std::enable_if_t<expr, std::nullptr_t> = nullptr
#define ENABLE_IF_T(...) ENABLE_IF_T_IMPL((__VA_ARGS__))
namespace internal_traits {
// 射影 (proj) の既定値
#if __cplusplus >= 202002L
using identity = std::identity;
#else
struct identity {
using is_transparent = void;
template <class T>
constexpr T&& operator()(T&& x) const noexcept {
return std::forward<T>(x);
}
};
#endif
} // namespace internal_traits
template <class C>
using mem_value_type = typename C::value_type;
template <class C>
using mem_difference_type = typename C::difference_type;
namespace internal_traits {
template <class T, class = void>
struct is_sorted_container_impl : std::false_type {};
template <class T>
struct is_sorted_container_impl<std::set<T>> : std::true_type {};
template <class T>
struct is_sorted_container_impl<std::multiset<T>> : std::true_type {};
} // namespace internal_traits
template <class T>
struct is_sorted_container : internal_traits::is_sorted_container_impl<T>::type {};
template <class T>
inline constexpr bool is_sorted_container_v = is_sorted_container<T>::value;
#line 16 "src/data_structures/dual-segtree.hpp"
/**
* @brief 双対セグメント木 (区間作用、1点取得)
*
* 区間への作用素の適用と1点の取得を O(log n) で行う。作用素は可換でなくてもよい
* 遅延伝搬セグメント木と違い、値のモノイドの演算 (op、e) は使わない
* 例:
* DualSegTree<acted_monoid::AffineSum<mint>> seg(v);
* seg.apply(l, r, Affine<mint>{b, c});
* mint x = seg.get(i);
*
* @tparam A 作用素付きモノイド (algebra/acted-monoid.hpp)
*/
template <typename A>
class DualSegTree {
public:
using S = typename A::S;
using F = typename A::F;
private:
A a;
long long n, sz;
int height;
std::vector<S> data; // 葉の値 (作用素をまだ適用していないもの)
std::vector<F> lazy; // 各ノードの区間に、まだ下へ伝えていない作用素
S mapping(const F& f, const S& x, long long k) const { return acted_monoid::apply_mapping(a, f, x, k, k + 1); }
F composition(const F& f, const F& g) const { return a.composition(f, g); }
F id() const { return a.id(); }
void apply_node(long long k, const F& f) { lazy[k] = composition(f, lazy[k]); }
void push(long long k) {
apply_node(2 * k, lazy[k]);
apply_node(2 * k + 1, lazy[k]);
lazy[k] = id();
}
// 葉 k の祖先の作用素をすべて下へ伝える
void push_ancestors(long long k) {
for (int h = height; h > 0; h--) push(k >> h);
}
void construct() {
sz = 1;
height = 0;
while (sz < n) {
sz <<= 1;
height++;
}
lazy.assign(2 * sz, id());
}
public:
/**
* @param n 要素数 各要素は S() で初期化する
* @param a 作用素付きモノイド
*/
explicit DualSegTree(long long n = 0, A a = A()) : DualSegTree(n, S(), std::move(a)) {}
/**
* @param n 要素数
* @param value 各要素の初期値
* @param a 作用素付きモノイド
*/
DualSegTree(long long n, const S& value, A a = A()) : a(std::move(a)), n(n), data(n, value) { construct(); }
/**
* @param v 初期の要素
* @param a 作用素付きモノイド
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit DualSegTree(R&& v, A a = A()) : a(std::move(a)), n(internal_traits::range_size(v)) {
data.reserve(n);
for (auto&& x : v) data.emplace_back(std::forward<decltype(x)>(x));
construct();
}
/**
* @brief 要素数を返す
*/
long long size() const { return n; }
/**
* @brief 指定された要素の値を返す O(log n)
*/
S get(long long k) const {
assert(0 <= k && k < n);
// 根に近いノードほど後に作用した作用素なので、葉から順に合成する
F f = id();
for (long long i = k + sz; i > 0; i >>= 1) f = composition(lazy[i], f);
return mapping(f, data[k], k);
}
/**
* @brief すべての要素の値を返す O(n)
*/
std::vector<S> to_vector() {
for (long long k = 1; k < sz; k++) push(k);
std::vector<S> res(n);
for (long long k = 0; k < n; k++) res[k] = mapping(lazy[k + sz], data[k], k);
return res;
}
/**
* @brief 指定された要素の値を x にする O(log n)
*/
void set(long long k, const S& x) {
assert(0 <= k && k < n);
push_ancestors(k + sz);
data[k] = x;
lazy[k + sz] = id();
}
/**
* @brief 1点作用 O(log n)
*/
void apply(long long k, const F& f) {
assert(0 <= k && k < n);
push_ancestors(k + sz);
apply_node(k + sz, f);
}
/**
* @brief [l, r) の区間の値に f を作用させる O(log n)
*/
void apply(long long l, long long r, const F& f) {
assert(0 <= l && l <= r && r <= n);
if (l == r) return;
l += sz;
r += sz;
// 作用する区間の境界の祖先に残っている作用素を先に下へ伝える (作用素が可換でなくても順序を保つため)
for (int h = height; h > 0; h--) {
if (((l >> h) << h) != l) push(l >> h);
if (((r >> h) << h) != r) push((r - 1) >> h);
}
for (; l < r; l >>= 1, r >>= 1) {
if (l & 1) apply_node(l++, f);
if (r & 1) apply_node(--r, f);
}
}
};
template <typename A>
DualSegTree(long long, A) -> DualSegTree<A>;
template <typename A>
DualSegTree(long long, typename A::S, A) -> DualSegTree<A>;
template <class R, typename A>
DualSegTree(R&&, A) -> DualSegTree<A>;
template <typename A>
DualSegTree(std::initializer_list<typename A::S>, A) -> DualSegTree<A>;
// 別名 双対セグメント木は op, e を使わないので、取得の部分を名前に含めない
// mapping が区間の長さを使わない Min 系を実体にする (値の型に S(sz) や掛け算を求めない)
/**
* @brief 区間加算、1点取得
*
* @tparam S 型
*/
template <typename S>
using RAddQ = DualSegTree<acted_monoid::AddMin<S>>;
/**
* @brief 区間代入、1点取得
*
* @tparam S 型
*/
template <typename S>
using RUpdateQ = DualSegTree<acted_monoid::UpdateMin<S>>;
/**
* @brief 区間 chmin、1点取得
*
* @tparam S 型
*/
template <typename S>
using RChminQ = DualSegTree<acted_monoid::ChminMin<S>>;
/**
* @brief 区間 chmax、1点取得
*
* @tparam S 型
*/
template <typename S>
using RChmaxQ = DualSegTree<acted_monoid::ChmaxMax<S>>;
/**
* @brief 区間アフィン変換 x <- a * x + b (Affine)、1点取得
*
* @tparam S 型
*/
template <typename S>
using RAffineQ = DualSegTree<acted_monoid::AffineSum<S>>;
#line 2 "src/data_structures/fenwick-tree.hpp"
/**
* @file fenwick-tree.hpp
* @brief Fenwick Tree (Binary Indexed Tree)
*/
#line 13 "src/data_structures/fenwick-tree.hpp"
#line 16 "src/data_structures/fenwick-tree.hpp"
/**
* @brief Fenwick Tree (Binary Indexed Tree)
*
* 1 点への作用と区間積を O(log n) で行う
* 例:
* FenwickTree<group::Sum<long long>> ft(n);
* ft.apply(i, x); // a[i] += x
* ft.prod(l, r); // a[l] + ... + a[r-1]
*
* @tparam G 可換な群 (algebra/group.hpp)。prefix_prod と max_right だけなら可換モノイドでもよい
*/
template <typename G>
class FenwickTree {
public:
using S = typename G::S;
private:
G g;
long long n;
// data[i] は a[i - (i & -i)] から a[i-1] までの積 (1-indexed)
std::vector<S> data;
S op(const S& a, const S& b) const { return g.op(a, b); }
S e() const { return g.e(); }
S inv(const S& a) const { return g.inv(a); }
public:
/**
* @brief 要素数 n で、すべての要素が単位元の Fenwick Tree を作る
*/
explicit FenwickTree(long long n = 0, G g = G()) : g(std::move(g)), n(n), data(n + 1, e()) {}
/**
* @brief v を初期値とする Fenwick Tree を作る O(n)
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit FenwickTree(R&& v, G g = G()) : FenwickTree(internal_traits::range_size(v), std::move(g)) {
auto it = internal_traits::range_begin(v);
for (long long i = 1; i <= n; i++) {
data[i] = op(data[i], S(*it));
++it;
long long j = i + (i & -i);
if (j <= n) data[j] = op(data[j], data[i]);
}
}
long long size() const { return n; }
/**
* @brief a[k] を op(a[k], x) にする O(log n)
*/
void apply(long long k, const S& x) {
assert(0 <= k && k < n);
for (k++; k <= n; k += k & -k) data[k] = op(data[k], x);
}
/**
* @brief a[0] から a[r-1] までの積 O(log n)
*/
S prefix_prod(long long r) const {
assert(0 <= r && r <= n);
S res = e();
for (; r > 0; r -= r & -r) res = op(data[r], res);
return res;
}
/**
* @brief a[l] から a[r-1] までの積 O(log n)。逆元を使う
*/
S prod(long long l, long long r) const {
assert(0 <= l && l <= r && r <= n);
return op(inv(prefix_prod(l)), prefix_prod(r));
}
S all_prod() const { return prefix_prod(n); }
/**
* @brief a[k] O(log n)。逆元を使う
*/
S get(long long k) const {
assert(0 <= k && k < n);
return prod(k, k + 1);
}
/**
* @brief a[k] を x にする O(log n)。逆元を使う
*/
void set(long long k, const S& x) { apply(k, op(inv(get(k)), x)); }
/**
* @brief f(prefix_prod(r)) = true となる最大の r を返す O(log n)
* f は単調 (ある r までは true でそれ以降は false) であること。f(e()) = true
*/
template <typename F>
long long max_right(F f) const {
assert(f(e()));
long long r = 0;
S sum = e();
long long step = 1;
while (step * 2 <= n) step *= 2;
for (; step > 0; step /= 2) {
if (r + step <= n && f(op(sum, data[r + step]))) {
r += step;
sum = op(sum, data[r]);
}
}
return r;
}
};
template <typename G>
FenwickTree(long long, G) -> FenwickTree<G>;
template <class R, typename G>
FenwickTree(R&&, G) -> FenwickTree<G>;
template <typename G>
FenwickTree(std::initializer_list<typename G::S>, G) -> FenwickTree<G>;
#line 2 "src/data_structures/imos.hpp"
/**
* @file imos.hpp
* @brief imos法で区間作用、1点取得
*/
#line 13 "src/data_structures/imos.hpp"
#line 16 "src/data_structures/imos.hpp"
/**
* @brief imos法で区間作用、1点取得する。
*
* 例: Imos<acted_monoid::AddSum<long long>> imos(n);
*
* @tparam A 作用素付きモノイド (algebra/acted-monoid.hpp)
* 作用素はアーベル群(可換群)をなし、inv を持つ必要がある 値のモノイドの演算は使わない
*/
template <typename A>
class Imos {
public:
using S = typename A::S;
using F = typename A::F;
private:
A a;
long long _n, t;
std::vector<S> data;
std::vector<F> lazy;
S mapping(const F& f, const S& x, long long k) const { return acted_monoid::apply_mapping(a, f, x, k, k + 1); }
F composition(const F& f, const F& g) const { return a.composition(f, g); }
F id() const { return a.id(); }
F inv(const F& f) const { return a.inv(f); }
public:
/**
* @param n 要素数 各要素は S() で初期化する
* @param a 作用素付きモノイド
*/
explicit Imos(long long n = 0, A a = A()) : Imos(n, S(), std::move(a)) {}
/**
* @param n 要素数
* @param value 各要素の初期値
* @param a 作用素付きモノイド
*/
Imos(long long n, const S& value, A a = A()) : a(std::move(a)), _n(n), t(n), data(n, value), lazy(n, this->a.id()) {}
/**
* @param value 各要素の初期値
* @param a 作用素付きモノイド
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit Imos(R&& value, A a = A()) : a(std::move(a)), _n(internal_traits::range_size(value)), t(_n), lazy(_n, this->a.id()) {
data.reserve(_n);
for (auto&& x : value) data.emplace_back(std::forward<decltype(x)>(x));
}
/**
* @brief 1点作用
* @param k インデックス
* @param f 作用素
*/
void apply(long long k, const F& f) {
assert(0 <= k && k < _n);
data[k] = mapping(f, data[k], k);
}
/**
* @brief [l, r)の区間の値にfを作用させる
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @param f 作用素
*/
void apply(long long l, long long r, const F& f) {
assert(0 <= l && l <= r && r <= _n);
if (l < _n) lazy[l] = composition(lazy[l], f);
if (r < _n) lazy[r] = composition(lazy[r], inv(f));
if (t > l) t = l;
}
/**
* @brief 指定された要素の値を返す
* @param k インデックス
* @return const S& 値
*/
const S& get(long long k) {
assert(0 <= k && k < _n);
while (t <= k) {
data[t] = mapping(lazy[t], data[t], t);
if (t + 1 < _n) {
lazy[t + 1] = composition(lazy[t], lazy[t + 1]);
}
lazy[t] = id();
t++;
}
return data[k];
}
};
template <typename A>
Imos(long long, A) -> Imos<A>;
template <typename A>
Imos(long long, typename A::S, A) -> Imos<A>;
template <class R, typename A>
Imos(R&&, A) -> Imos<A>;
template <typename A>
Imos(std::initializer_list<typename A::S>, A) -> Imos<A>;
#line 2 "src/data_structures/lazy-segtree.hpp"
/**
* @file lazy-segtree.hpp
* @brief 遅延伝搬セグメント木
*/
#line 15 "src/data_structures/lazy-segtree.hpp"
#line 18 "src/data_structures/lazy-segtree.hpp"
/**
* @brief 遅延伝搬セグメント木
*
* 例:
* LazySegTree<acted_monoid::AffineSum<mint>> seg(v);
*
* @tparam A 作用素付きモノイド (algebra/acted-monoid.hpp)
*/
template <typename A>
class LazySegTree {
public:
using S = typename A::S;
using F = typename A::F;
private:
A a;
S op(const S& x, const S& y) const { return a.op(x, y); }
S e() const { return a.e(); }
S mapping(const F& f, const S& x, long long l, long long r) const { return acted_monoid::apply_mapping(a, f, x, l, r); }
F composition(const F& f, const F& g) const { return a.composition(f, g); }
F id() const { return a.id(); }
long long n, sz;
int height;
std::vector<S> data;
std::vector<F> lazy;
void update(long long k) { data[k] = op(data[2 * k], data[2 * k + 1]); }
void apply_node(long long k, int h, const F& f) {
// 末尾の要素数を 2 べきにそろえるための余りの部分は区間に含めない
long long l = std::min((k << h) & (sz - 1), n);
long long r = std::min(((k << h) & (sz - 1)) + (1LL << h), n);
data[k] = mapping(f, data[k], l, r);
if (k < sz) lazy[k] = composition(f, lazy[k]);
}
void push(long long k, int h) {
apply_node(2 * k, h - 1, lazy[k]);
apply_node(2 * k + 1, h - 1, lazy[k]);
lazy[k] = id();
}
class LazySegTreeReference {
LazySegTree& segtree;
long long k;
public:
LazySegTreeReference(LazySegTree& segtree, long long k) : segtree(segtree), k(k) {}
LazySegTreeReference& operator=(const S& x) {
segtree.set(k, x);
return *this;
}
operator S() { return segtree.get(k); }
};
void construct_data() {
sz = 1;
height = 0;
while (sz < n) {
sz <<= 1;
height++;
}
data.assign(sz * 2, e());
lazy.assign(sz * 2, id());
}
public:
/**
* @brief コンストラクタ
*
* @param n 要素数
* @param a 作用素付きモノイド
*/
explicit LazySegTree(long long n = 0, A a = A()) : a(std::move(a)), n(n) {
construct_data();
}
/**
* @brief コンストラクタ
*
* @param v 初期の要素
* @param a 作用素付きモノイド
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit LazySegTree(R&& v, A a = A()) : LazySegTree(internal_traits::range_size(v), std::move(a)) {
long long k = sz;
for (auto&& x : v) data[k++] = S(std::forward<decltype(x)>(x));
for (long long i = sz - 1; i > 0; i--) update(i);
}
/**
* @brief 要素数を返す
*/
long long size() const { return n; }
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S get(long long k) {
assert(0 <= k && k < n);
k += sz;
for (int h = height; h > 0; h--) {
push(k >> h, h);
}
return data[k];
}
/**
* @brief 指定された要素への参照を返す
*
* @param k
* @return SegTreeReference 要素への参照 代入されるとset()が呼ばれる
*/
LazySegTreeReference operator[](long long k) { return LazySegTreeReference(*this, k); }
/**
* @brief 内容を出力する
*
* @tparam CharT 出力ストリームの文字型
* @tparam Traits 出力ストリームの文字型特性
* @param os 出力ストリーム
* @param rhs セグメント木
* @return std::basic_ostream<CharT, Traits>& 出力ストリーム
*/
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, LazySegTree& rhs) {
for (long long i = 0; i < rhs.n; i++) {
if (i != 0) os << CharT(' ');
os << rhs[i];
}
return os;
}
/**
* @brief 指定された要素の値をxに更新する
*
* @param k インデックス
* @param x 新しい値
*/
void set(long long k, const S& x) {
assert(0 <= k && k < n);
k += sz;
for (int h = height; h > 0; h--) {
push(k >> h, h);
}
data[k] = x;
while (k >>= 1) update(k);
}
/**
* @brief [l, r)の区間の総積を返す
*
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @return S 総積
*/
S prod(long long l, long long r) {
assert(0 <= l && l <= r && r <= n);
l += sz;
r += sz;
for (int h = height; h > 0; h--) {
if (((l >> h) << h) != l) push(l >> h, h);
if (((r >> h) << h) != r) push(r >> h, h);
}
S left_prod = e(), right_prod = e();
while (l < r) {
if (l & 1) left_prod = op(left_prod, data[l++]);
if (r & 1) right_prod = op(data[--r], right_prod);
l >>= 1;
r >>= 1;
}
return op(left_prod, right_prod);
}
/**
* @brief すべての要素の総積を返す
*
* @return S 総積
*/
S all_prod() const { return data[1]; }
/**
* @brief 指定された要素の値にfを作用させる
*
* @param k インデックス
* @param f 作用素
*/
void apply(long long k, const F& f) {
assert(0 <= k && k < n);
k += sz;
for (int h = height; h > 0; h--) {
push(k >> h, h);
}
data[k] = mapping(f, data[k], k - sz, k - sz + 1);
while (k >>= 1) update(k);
}
/**
* @brief [l, r)の区間の値にxを作用させる
*
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @param f 作用素
*/
void apply(long long l, long long r, const F& f) {
assert(0 <= l && l <= r && r <= n);
if (l == r) return;
l += sz;
r += sz;
for (int h = height; h > 0; h--) {
if (((l >> h) << h) != l) push(l >> h, h);
if (((r >> h) << h) != r) push(r >> h, h);
}
{
long long l2 = l, r2 = r;
int h = 0;
while (l < r) {
if (l & 1) apply_node(l++, h, f);
if (r & 1) apply_node(--r, h, f);
l >>= 1;
r >>= 1;
h++;
}
l = l2;
r = r2;
}
for (int h = 1; h <= height; h++) {
if (((l >> h) << h) != l) update(l >> h);
if (((r >> h) << h) != r) update((r - 1) >> h);
}
}
/**
* @brief (r = l or g(prod([l, r))) = true) and (r = n or g(prod([l, r+1))) = false)となるrを返す
* gが単調なら、g(prod([l, r))) = trueとなる最大のr
*
* @tparam G
* @param l 半開区間の開始 0<=l<=n
* @param g 判定関数 g(e) = true
* @return long long
*/
template <typename G>
long long max_right(long long l, G g) {
assert(g(e()));
assert(0 <= l && l <= n);
if (l == n) return n;
l += sz;
for (int h = height; h > 0; h--) {
push(l >> h, h);
}
int h = 0;
while (l % 2 == 0) {
l >>= 1;
h++;
}
S sum = e();
while (g(op(sum, data[l]))) {
sum = op(sum, data[l]);
l++;
while (l % 2 == 0) {
l >>= 1;
h++;
}
if (l == 1) return n;
}
while (l < sz) {
push(l, h);
if (!g(op(sum, data[l * 2]))) {
l = l * 2;
} else {
sum = op(sum, data[l * 2]);
l = l * 2 + 1;
}
h--;
}
return l - sz;
}
/**
* @brief (l = 0 or g(prod([l, r))) = true) and (l = r or g(prod([l-1, r))) = false)となるlを返す
* gが単調なら、g(prod([l, r))) = trueとなる最小のl
*
* @tparam G
* @param r 半開区間の終端 0<=r<=n
* @param g 判定関数 g(e) = true
* @return long long
*/
template <typename G>
long long min_left(long long r, G g) {
assert(g(e()));
assert(0 <= r && r <= n);
if (r == 0) return 0;
r += sz;
for (int h = height; h > 0; h--) {
push((r - 1) >> h, h);
}
int h = 0;
S sum = e();
do {
r--;
while (r > 1 && r % 2 == 1) {
r >>= 1;
h++;
}
if (!g(op(data[r], sum))) {
while (r < sz) {
push(r, h);
r = r * 2 + 1;
h--;
if (g(op(data[r], sum))) {
sum = op(data[r], sum);
r--;
}
}
return r + 1 - sz;
}
sum = op(data[r], sum);
} while ((r & -r) != r);
return 0;
}
};
template <typename A>
LazySegTree(long long, A) -> LazySegTree<A>;
template <class R, typename A>
LazySegTree(R&&, A) -> LazySegTree<A>;
template <typename A>
LazySegTree(std::initializer_list<typename A::S>, A) -> LazySegTree<A>;
/**
* @brief 区間最小値更新、区間最小値
*
* @tparam S 型
*/
template <typename S>
using RChminMinQ = LazySegTree<acted_monoid::ChminMin<S>>;
/**
* @brief 区間最大値更新、区間最大値
*
* @tparam S 型
*/
template <typename S>
using RChmaxMaxQ = LazySegTree<acted_monoid::ChmaxMax<S>>;
/**
* @brief 区間加算、区間最小値
*
* @tparam S 型
*/
template <typename S>
using RAddMinQ = LazySegTree<acted_monoid::AddMin<S>>;
/**
* @brief 区間加算、区間最大値
*
* @tparam S 型
*/
template <typename S>
using RAddMaxQ = LazySegTree<acted_monoid::AddMax<S>>;
/**
* @brief 区間加算、区間和
*
* @tparam S 型
*/
template <typename S>
using RAddSumQ = LazySegTree<acted_monoid::AddSum<S>>;
/**
* @brief 区間変更、区間最小値
*
* @tparam S 型
*/
template <typename S>
using RUpdateMinQ = LazySegTree<acted_monoid::UpdateMin<S>>;
/**
* @brief 区間変更、区間最大値
*
* @tparam S 型
*/
template <typename S>
using RUpdateMaxQ = LazySegTree<acted_monoid::UpdateMax<S>>;
/**
* @brief 区間変更、区間和
*
* @tparam S 型
*/
template <typename S>
using RUpdateSumQ = LazySegTree<acted_monoid::UpdateSum<S>>;
#line 2 "src/data_structures/link-cut-tree.hpp"
/**
* @file link-cut-tree.hpp
* @brief Link-Cut Tree
*/
#line 13 "src/data_structures/link-cut-tree.hpp"
#line 15 "src/data_structures/link-cut-tree.hpp"
/**
* @brief Link-Cut Tree (森で、辺の追加・削除とパス上の値の集約ができる)
*
* 各操作はならし O(log n)。内部の配列は int で持つ
* 例:
* LinkCutTree<monoid::Sum<long long>> lct(a);
* lct.link(0, 1);
* long long s = lct.prod(0, 1);
*
* @tparam M モノイド (algebra/monoid.hpp)。可換でなくてもよい (prod は u から v の向きにたたむ)
*/
template <typename M>
class LinkCutTree {
using S = typename M::S;
struct Node {
int l = -1, r = -1, p = -1;
bool rev = false;
S val, sum, rsum; // sum は左から右、rsum は右から左にたたんだもの
};
M m;
S op(const S& a, const S& b) const { return m.op(a, b); }
S e() const { return m.e(); }
std::vector<Node> t;
std::vector<int> stk;
bool is_root(int x) const {
int p = t[x].p;
return p == -1 || (t[p].l != x && t[p].r != x);
}
S sum(int x) const { return x == -1 ? e() : t[x].sum; }
S rsum(int x) const { return x == -1 ? e() : t[x].rsum; }
void update(int x) {
t[x].sum = op(op(sum(t[x].l), t[x].val), sum(t[x].r));
t[x].rsum = op(op(rsum(t[x].r), t[x].val), rsum(t[x].l));
}
void toggle(int x) {
if (x == -1) return;
std::swap(t[x].l, t[x].r);
std::swap(t[x].sum, t[x].rsum);
t[x].rev = !t[x].rev;
}
void push(int x) {
if (!t[x].rev) return;
toggle(t[x].l);
toggle(t[x].r);
t[x].rev = false;
}
void rotate(int x) {
int p = t[x].p, g = t[p].p;
if (t[p].l == x) {
t[p].l = t[x].r;
if (t[x].r != -1) t[t[x].r].p = p;
t[x].r = p;
} else {
t[p].r = t[x].l;
if (t[x].l != -1) t[t[x].l].p = p;
t[x].l = p;
}
t[p].p = x, t[x].p = g;
if (g != -1) {
if (t[g].l == p) t[g].l = x;
if (t[g].r == p) t[g].r = x;
}
update(p), update(x);
}
void splay(int x) {
for (int y = x;; y = t[y].p) {
stk.push_back(y);
if (is_root(y)) break;
}
while (!stk.empty()) push(stk.back()), stk.pop_back();
while (!is_root(x)) {
int p = t[x].p;
if (!is_root(p)) rotate((t[t[p].p].l == p) == (t[p].l == x) ? p : x);
rotate(x);
}
}
// x から根までのパスを 1 本の splay 木にし、x をその根にする。最後に splay した頂点を返す
int access(int x) {
int last = -1;
for (int y = x; y != -1; y = t[y].p) {
splay(y);
t[y].r = last;
update(y);
last = y;
}
splay(x);
return last;
}
public:
/**
* @brief 頂点数 n、辺なし、値はすべて単位元
*
* @param m モノイド
*/
explicit LinkCutTree(long long n = 0, M m = M()) : m(std::move(m)) {
Node x;
x.val = x.sum = x.rsum = e();
t.assign(n, x);
}
/**
* @brief 頂点 i の値が a[i]、辺なし
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit LinkCutTree(R&& a, M m = M()) : LinkCutTree(internal_traits::range_size(a), std::move(m)) {
long long i = 0;
for (auto&& x : a) {
t[i].val = t[i].sum = t[i].rsum = S(std::forward<decltype(x)>(x));
++i;
}
}
/**
* @brief 頂点数
*/
long long size() const { return static_cast<long long>(t.size()); }
/**
* @brief v を根にする
*/
void evert(long long v) {
access(v);
toggle(v);
push(v);
}
/**
* @brief 辺 (u, v) を追加する。u と v は別の木にあること
*/
void link(long long u, long long v) {
assert(!connected(u, v));
evert(u);
t[u].p = static_cast<int>(v);
}
/**
* @brief 辺 (u, v) を削除する。辺 (u, v) があること
*/
void cut(long long u, long long v) {
evert(u);
access(v);
assert(t[v].l == u && t[u].r == -1);
t[v].l = t[u].p = -1;
update(v);
}
/**
* @brief v を含む木の根
*/
long long root(long long v) {
access(v);
int x = static_cast<int>(v);
while (push(x), t[x].l != -1) x = t[x].l;
splay(x);
return x;
}
/**
* @brief u と v が同じ木にあるか
*/
bool connected(long long u, long long v) { return u == v || root(u) == root(v); }
/**
* @brief u と v の最小共通祖先 (根は最後に evert した頂点など、今の根)。u と v は同じ木にあること
*/
long long lca(long long u, long long v) {
assert(connected(u, v));
access(u);
return access(v);
}
/**
* @brief 頂点 v の値を x にする
*/
void set(long long v, const S& x) {
access(v);
t[v].val = x;
update(v);
}
/**
* @brief 頂点 v の値
*/
S get(long long v) const { return t[v].val; }
/**
* @brief 頂点 v の値を op(get(v), x) にする
*/
void apply(long long v, const S& x) { set(v, op(t[v].val, x)); }
/**
* @brief u から v へのパス上の頂点 (端点を含む) の値を、u の側から順にたたんだもの。u と v は同じ木にあること
*
* u が根になる
*/
S prod(long long u, long long v) {
assert(connected(u, v));
evert(u);
access(v);
return t[v].sum;
}
};
/**
* @brief 部分木の値の集約もできる Link-Cut Tree
*
* パスに含まれない子の部分木の値 (virtual) を持つ。各操作はならし O(log n)
* 例:
* SubtreeLinkCutTree<group::Sum<long long>> lct(a);
* lct.link(0, 1);
* long long s = lct.subtree_prod(1, 0); // 0 を親としたときの 1 の部分木の和
*
* @tparam G 可換な群 (algebra/group.hpp)
*/
template <typename M>
LinkCutTree(long long, M) -> LinkCutTree<M>;
template <class R, typename M>
LinkCutTree(R&&, M) -> LinkCutTree<M>;
template <typename M>
LinkCutTree(std::initializer_list<typename M::S>, M) -> LinkCutTree<M>;
template <typename G>
class SubtreeLinkCutTree {
using S = typename G::S;
struct Node {
int l = -1, r = -1, p = -1;
bool rev = false;
S val, path, virt, sum; // path はパス上、sum は virtual も含めた和
};
G g;
S op(const S& a, const S& b) const { return g.op(a, b); }
S e() const { return g.e(); }
S inv(const S& a) const { return g.inv(a); }
std::vector<Node> t;
std::vector<int> stk;
bool is_root(int x) const {
int p = t[x].p;
return p == -1 || (t[p].l != x && t[p].r != x);
}
S path(int x) const { return x == -1 ? e() : t[x].path; }
S sum(int x) const { return x == -1 ? e() : t[x].sum; }
void update(int x) {
t[x].path = op(op(path(t[x].l), t[x].val), path(t[x].r));
t[x].sum = op(op(sum(t[x].l), op(t[x].val, t[x].virt)), sum(t[x].r));
}
void toggle(int x) {
if (x == -1) return;
std::swap(t[x].l, t[x].r);
t[x].rev = !t[x].rev;
}
void push(int x) {
if (!t[x].rev) return;
toggle(t[x].l);
toggle(t[x].r);
t[x].rev = false;
}
void rotate(int x) {
int p = t[x].p, g = t[p].p;
if (t[p].l == x) {
t[p].l = t[x].r;
if (t[x].r != -1) t[t[x].r].p = p;
t[x].r = p;
} else {
t[p].r = t[x].l;
if (t[x].l != -1) t[t[x].l].p = p;
t[x].l = p;
}
t[p].p = x, t[x].p = g;
if (g != -1) {
if (t[g].l == p) t[g].l = x;
if (t[g].r == p) t[g].r = x;
}
update(p), update(x);
}
void splay(int x) {
for (int y = x;; y = t[y].p) {
stk.push_back(y);
if (is_root(y)) break;
}
while (!stk.empty()) push(stk.back()), stk.pop_back();
while (!is_root(x)) {
int p = t[x].p;
if (!is_root(p)) rotate((t[t[p].p].l == p) == (t[p].l == x) ? p : x);
rotate(x);
}
}
int access(int x) {
int last = -1;
for (int y = x; y != -1; y = t[y].p) {
splay(y);
// 今の右の子は virtual になり、last は virtual でなくなる
t[y].virt = op(op(t[y].virt, sum(t[y].r)), inv(sum(last)));
t[y].r = last;
update(y);
last = y;
}
splay(x);
return last;
}
public:
explicit SubtreeLinkCutTree(long long n = 0, G g = G()) : g(std::move(g)) {
Node x;
x.val = x.path = x.virt = x.sum = e();
t.assign(n, x);
}
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit SubtreeLinkCutTree(R&& a, G g = G()) : SubtreeLinkCutTree(internal_traits::range_size(a), std::move(g)) {
long long i = 0;
for (auto&& x : a) {
t[i].val = t[i].path = t[i].sum = S(std::forward<decltype(x)>(x));
++i;
}
}
long long size() const { return static_cast<long long>(t.size()); }
void evert(long long v) {
access(v);
toggle(v);
push(v);
}
void link(long long u, long long v) {
assert(!connected(u, v));
evert(u);
access(v);
t[u].p = static_cast<int>(v);
t[v].virt = op(t[v].virt, t[u].sum);
update(v);
}
void cut(long long u, long long v) {
evert(u);
access(v);
assert(t[v].l == u && t[u].r == -1);
t[v].l = t[u].p = -1;
update(v);
}
long long root(long long v) {
access(v);
int x = static_cast<int>(v);
while (push(x), t[x].l != -1) x = t[x].l;
splay(x);
return x;
}
bool connected(long long u, long long v) { return u == v || root(u) == root(v); }
long long lca(long long u, long long v) {
assert(connected(u, v));
access(u);
return access(v);
}
void set(long long v, const S& x) {
access(v);
t[v].val = x;
update(v);
}
S get(long long v) const { return t[v].val; }
void apply(long long v, const S& x) { set(v, op(t[v].val, x)); }
/**
* @brief u から v へのパス上の頂点 (端点を含む) の値の和。u と v は同じ木にあること
*/
S prod(long long u, long long v) {
assert(connected(u, v));
evert(u);
access(v);
return t[v].path;
}
/**
* @brief p を根としたときの v の部分木の値の和 (p == v なら木全体)。v と p は同じ木にあること
*
* p が根になる
*/
S subtree_prod(long long v, long long p) {
assert(connected(v, p));
evert(p);
access(v);
return op(t[v].val, t[v].virt);
}
};
template <typename G>
SubtreeLinkCutTree(long long, G) -> SubtreeLinkCutTree<G>;
template <class R, typename G>
SubtreeLinkCutTree(R&&, G) -> SubtreeLinkCutTree<G>;
template <typename G>
SubtreeLinkCutTree(std::initializer_list<typename G::S>, G) -> SubtreeLinkCutTree<G>;
#line 2 "src/data_structures/monoid-unionfind.hpp"
/**
* @file monoid-unionfind.hpp
* @brief 可換モノイドを乗せるUnionFind
*/
#line 13 "src/data_structures/monoid-unionfind.hpp"
#line 2 "src/data_structures/unionfind.hpp"
/**
* @file unionfind.hpp
* @brief UnionFind
*/
#line 12 "src/data_structures/unionfind.hpp"
namespace internal_unionfind {
/**
* @brief 各要素の代表元から、連結成分ごとの要素のリストを作る
* @param leader 要素 a の代表元を返す関数
*/
template <typename F>
std::vector<std::vector<long long>> groups(long long n, F leader) {
std::vector<long long> leader_buf(n), group_size(n);
for (long long i = 0; i < n; i++) {
leader_buf[i] = leader(i);
group_size[leader_buf[i]]++;
}
std::vector<std::vector<long long>> result(n);
for (long long i = 0; i < n; i++) {
result[i].reserve(group_size[i]);
}
for (long long i = 0; i < n; i++) {
result[leader_buf[i]].push_back(i);
}
result.erase(std::remove_if(result.begin(), result.end(), [&](const std::vector<long long>& v) { return v.empty(); }), result.end());
return result;
}
} // namespace internal_unionfind
/**
* @brief 無向グラフに対して「辺の追加」、「2頂点が連結かの判定」をする
*/
class UnionFind {
protected:
long long _n;
// 負ならサイズ、非負なら親 (メモリを抑えるため int で持つ)
std::vector<int> parent_or_size;
public:
/**
* @brief merge の戻り値
*
* if (uf.merge(a, b)) で新しく統合したかを判定でき、
* auto [r, merged] = uf.merge(a, b); で代表元も受け取れる
*/
struct MergeResult {
long long leader; //!< 統合後の代表元
bool merged; //!< 新しく統合したか (もともと同じ連結成分なら false)
explicit operator bool() const { return merged; }
};
UnionFind() : _n(0) {}
explicit UnionFind(long long n) : _n(n), parent_or_size(n, -1) {}
/**
* @brief 辺(a,b)を足す
* @return 統合後の代表元と、新しく統合したか
*/
MergeResult merge(long long a, long long b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
long long x = leader(a), y = leader(b);
if (x == y) return {x, false};
if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y);
parent_or_size[x] += parent_or_size[y];
parent_or_size[y] = static_cast<int>(x);
return {x, true};
}
/**
* @brief 頂点a,bが連結かどうか
*/
bool same(long long a, long long b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
return leader(a) == leader(b);
}
/**
* @brief 頂点aの属する連結成分の代表元
*/
long long leader(long long a) {
assert(0 <= a && a < _n);
if (parent_or_size[a] < 0) return a;
int x = static_cast<int>(a);
while (parent_or_size[x] >= 0) {
x = parent_or_size[x];
}
while (parent_or_size[a] >= 0) {
int t = parent_or_size[a];
parent_or_size[a] = x;
a = t;
}
return x;
}
/**
* @brief 頂点aの属する連結成分のサイズ
*/
long long size(long long a) {
assert(0 <= a && a < _n);
return -parent_or_size[leader(a)];
}
/**
* @brief グラフを連結成分に分け、その情報を返す
* @return 「一つの連結成分の頂点番号のリスト」のリスト
*/
std::vector<std::vector<long long>> groups() {
return internal_unionfind::groups(_n, [&](long long a) { return leader(a); });
}
};
#line 17 "src/data_structures/monoid-unionfind.hpp"
/**
* @brief 可換モノイドを乗せるUnionFind
*
* @tparam M 可換モノイド (algebra/monoid.hpp)
*/
template <typename M>
class MonoidUnionFind : private UnionFind {
public:
using S = typename M::S;
private:
M m;
std::vector<S> val;
using UnionFind::_n;
using UnionFind::parent_or_size;
public:
/**
* @param n 要素数 各要素の値は単位元で初期化する
* @param m 可換モノイド
*/
explicit MonoidUnionFind(long long n = 0, M m = M()) : UnionFind(n), m(std::move(m)), val(n, this->m.e()) {}
/**
* @param v 各要素の初期値
* @param m 可換モノイド
*/
explicit MonoidUnionFind(std::vector<S> v, M m = M()) : UnionFind(v.size()), m(std::move(m)), val(std::move(v)) {}
/**
* @brief 各要素を S(x) で構築して初期化する
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit MonoidUnionFind(R&& v, M m = M())
: UnionFind(internal_traits::range_size(v)), m(std::move(m)) {
val.reserve(internal_traits::range_size(v));
for (auto&& x : v) val.emplace_back(std::forward<decltype(x)>(x));
}
using MergeResult = UnionFind::MergeResult;
using UnionFind::groups;
using UnionFind::leader;
using UnionFind::same;
using UnionFind::size;
/**
* @brief a と b の連結成分を統合し、値の積を取る
* @return 統合後の代表元と、新しく統合したか
*/
MergeResult merge(long long a, long long b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
long long x = leader(a), y = leader(b);
if (x == y) return {x, false};
if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y);
parent_or_size[x] += parent_or_size[y];
parent_or_size[y] = static_cast<int>(x);
val[x] = m.op(val[x], val[y]);
return {x, true};
}
/**
* @brief 要素aの属する連結成分の値の総積
*/
const S& prod(long long a) {
return val[leader(a)];
}
};
template <typename M>
MonoidUnionFind(long long, M) -> MonoidUnionFind<M>;
template <class R, typename M>
MonoidUnionFind(R&&, M) -> MonoidUnionFind<M>;
template <typename M>
MonoidUnionFind(std::initializer_list<typename M::S>, M) -> MonoidUnionFind<M>;
#line 2 "src/data_structures/persistent-lazy-segtree.hpp"
/**
* @file persistent-lazy-segtree.hpp
* @brief 永続遅延伝搬セグメント木
*/
#line 11 "src/data_structures/persistent-lazy-segtree.hpp"
#include <memory>
#line 16 "src/data_structures/persistent-lazy-segtree.hpp"
#line 19 "src/data_structures/persistent-lazy-segtree.hpp"
/**
* @brief 永続遅延伝搬セグメント木
*
* 更新すると新しい版を返し、元の版は変わらない。同じ木から作った版はノードを共有する
* 別の版の区間をそのまま写した版も作れる
* 例:
* PersistentLazySegTree<acted_monoid::AffineSum<mint>> s0(v);
* auto s1 = s0.apply(l, r, Affine<mint>{b, c}); // s0 はそのまま
* auto s2 = s1.copy(s0, l, r); // [l, r) を s0 の値に戻した版
*
* @tparam A 作用素付きモノイド (algebra/acted-monoid.hpp)
*/
template <typename A>
class PersistentLazySegTree {
public:
using S = typename A::S;
using F = typename A::F;
private:
// すべての版のノードを持つ。ノードは削除しない
// val はノードの区間の積で、そのノードの lazy は適用済み。lazy は子にまだ伝えていない作用素
struct Pool {
A a;
std::vector<S> val;
std::vector<F> lazy;
std::vector<int> left, right; // 葉では -1
explicit Pool(A a) : a(std::move(a)) {}
int make_leaf(const S& x) {
val.push_back(x);
lazy.push_back(a.id());
left.push_back(-1);
right.push_back(-1);
return static_cast<int>(val.size()) - 1;
}
int make_node(int l, int r) {
val.push_back(a.op(val[l], val[r]));
lazy.push_back(a.id());
left.push_back(l);
right.push_back(r);
return static_cast<int>(val.size()) - 1;
}
};
std::shared_ptr<Pool> pool;
long long n, sz;
int root;
S op(const S& x, const S& y) const { return pool->a.op(x, y); }
S e() const { return pool->a.e(); }
// 末尾の要素数を 2 べきにそろえるための余りの部分は区間に含めない
S mapping(const F& f, const S& x, long long a, long long b) const { return acted_monoid::apply_mapping(pool->a, f, x, std::min(a, n), std::min(b, n)); }
F composition(const F& f, const F& g) const { return pool->a.composition(f, g); }
F id() const { return pool->a.id(); }
PersistentLazySegTree(std::shared_ptr<Pool> pool, long long n, long long sz, int root) : pool(std::move(pool)), n(n), sz(sz), root(root) {}
void init_size() {
sz = 1;
while (sz < n) sz <<= 1;
}
template <class It>
int build(It& it, long long a, long long b) {
if (b - a == 1) {
if (a >= n) return pool->make_leaf(e());
S x(*it);
++it;
return pool->make_leaf(x);
}
long long mid = (a + b) / 2;
int l = build(it, a, mid);
int r = build(it, mid, b);
return pool->make_node(l, r);
}
// ノード t ([a, b)) に f を作用させた新しいノード
int apply_node(int t, long long a, long long b, const F& f) const {
S x = mapping(f, pool->val[t], a, b);
if (b - a == 1) return pool->make_leaf(x);
F g = composition(f, pool->lazy[t]);
int l = pool->left[t], r = pool->right[t];
pool->val.push_back(x);
pool->lazy.push_back(g);
pool->left.push_back(l);
pool->right.push_back(r);
return static_cast<int>(pool->val.size()) - 1;
}
// ノード t ([a, b)) の lazy を子に伝えた、新しい子の組
std::pair<int, int> push(int t, long long a, long long b) const {
long long mid = (a + b) / 2;
const F f = pool->lazy[t];
int l = apply_node(pool->left[t], a, mid, f);
int r = apply_node(pool->right[t], mid, b, f);
return {l, r};
}
int set_rec(int t, long long a, long long b, long long k, const S& x) const {
if (b - a == 1) return pool->make_leaf(x);
long long mid = (a + b) / 2;
auto [l, r] = push(t, a, b);
if (k < mid)
l = set_rec(l, a, mid, k, x);
else
r = set_rec(r, mid, b, k, x);
return pool->make_node(l, r);
}
int apply_rec(int t, long long a, long long b, long long l, long long r, const F& f) const {
if (r <= a || b <= l) return t;
if (l <= a && b <= r) return apply_node(t, a, b, f);
long long mid = (a + b) / 2;
auto [lc, rc] = push(t, a, b);
lc = apply_rec(lc, a, mid, l, r, f);
rc = apply_rec(rc, mid, b, l, r, f);
return pool->make_node(lc, rc);
}
// t の [l, r) を u に置き換える。f は u の祖先にあって、まだ u に適用していない作用素
int copy_rec(int t, int u, long long a, long long b, long long l, long long r, const F& f) const {
if (r <= a || b <= l) return t;
if (l <= a && b <= r) return apply_node(u, a, b, f);
long long mid = (a + b) / 2;
auto [lc, rc] = push(t, a, b);
F g = composition(f, pool->lazy[u]);
lc = copy_rec(lc, pool->left[u], a, mid, l, r, g);
rc = copy_rec(rc, pool->right[u], mid, b, l, r, g);
return pool->make_node(lc, rc);
}
// f はノード t の祖先にあって、まだ t に適用していない作用素
S prod_rec(int t, long long a, long long b, long long l, long long r, const F& f) const {
if (r <= a || b <= l) return e();
if (l <= a && b <= r) return mapping(f, pool->val[t], a, b);
long long mid = (a + b) / 2;
F g = composition(f, pool->lazy[t]);
return op(prod_rec(pool->left[t], a, mid, l, r, g), prod_rec(pool->right[t], mid, b, l, r, g));
}
// [a, b) のうち l 以降で、sum に掛けると g が偽になる最初の位置 (なければ b)
template <typename G>
long long max_right_rec(int t, long long a, long long b, long long l, G& g, S& sum, const F& f) const {
if (b <= l) return b;
if (l <= a) {
S s = op(sum, mapping(f, pool->val[t], a, b));
if (g(s)) {
sum = s;
return b;
}
if (b - a == 1) return a;
}
long long mid = (a + b) / 2;
F h = composition(f, pool->lazy[t]);
long long x = max_right_rec(pool->left[t], a, mid, l, g, sum, h);
if (x < mid) return x;
return max_right_rec(pool->right[t], mid, b, l, g, sum, h);
}
// [a, b) のうち r より前で、sum に左から掛けると g が偽になる最後の位置 + 1 (なければ a)
template <typename G>
long long min_left_rec(int t, long long a, long long b, long long r, G& g, S& sum, const F& f) const {
if (r <= a) return a;
if (b <= r) {
S s = op(mapping(f, pool->val[t], a, b), sum);
if (g(s)) {
sum = s;
return a;
}
if (b - a == 1) return b;
}
long long mid = (a + b) / 2;
F h = composition(f, pool->lazy[t]);
long long x = min_left_rec(pool->right[t], mid, b, r, g, sum, h);
if (x > mid) return x;
return min_left_rec(pool->left[t], a, mid, r, g, sum, h);
}
public:
/**
* @brief コンストラクタ
*
* すべての要素を単位元で初期化する。単位元の部分木は共有するので、n が大きくても O(log n) で作れる
*
* @param n 要素数
* @param a 作用素付きモノイド
*/
explicit PersistentLazySegTree(long long n = 0, A a = A()) : pool(std::make_shared<Pool>(std::move(a))), n(n) {
assert(0 <= n);
init_size();
root = pool->make_leaf(e());
for (long long w = 1; w < sz; w <<= 1) root = pool->make_node(root, root);
}
/**
* @brief コンストラクタ
*
* @param v 初期の要素
* @param a 作用素付きモノイド
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit PersistentLazySegTree(R&& v, A a = A()) : pool(std::make_shared<Pool>(std::move(a))), n(internal_traits::range_size(v)) {
init_size();
auto it = internal_traits::range_begin(v);
root = build(it, 0, sz);
}
/**
* @brief 要素数を返す
*/
long long size() const { return n; }
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S get(long long k) const {
assert(0 <= k && k < n);
int t = root;
long long a = 0, b = sz;
F f = id();
while (b - a > 1) {
f = composition(f, pool->lazy[t]);
long long mid = (a + b) / 2;
if (k < mid) {
t = pool->left[t];
b = mid;
} else {
t = pool->right[t];
a = mid;
}
}
return mapping(f, pool->val[t], a, b);
}
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S operator[](long long k) const { return get(k); }
/**
* @brief 内容を出力する
*
* @tparam CharT 出力ストリームの文字型
* @tparam Traits 出力ストリームの文字型特性
* @param os 出力ストリーム
* @param rhs 永続遅延伝搬セグメント木
* @return std::basic_ostream<CharT, Traits>& 出力ストリーム
*/
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const PersistentLazySegTree& rhs) {
for (long long i = 0; i < rhs.n; i++) {
if (i != 0) os << CharT(' ');
os << rhs[i];
}
return os;
}
/**
* @brief 指定された要素の値をxにした新しい版を返す
*
* @param k インデックス
* @param x 新しい値
* @return PersistentLazySegTree 新しい版 (自身は変わらない)
*/
PersistentLazySegTree set(long long k, const S& x) const {
assert(0 <= k && k < n);
return PersistentLazySegTree(pool, n, sz, set_rec(root, 0, sz, k, x));
}
/**
* @brief [l, r)の区間の総積を返す
*
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @return S 総積
*/
S prod(long long l, long long r) const {
assert(0 <= l && l <= r && r <= n);
return prod_rec(root, 0, sz, l, r, id());
}
/**
* @brief すべての要素の総積を返す
*
* @return S 総積
*/
S all_prod() const { return pool->val[root]; }
/**
* @brief 指定された要素の値にfを作用させた新しい版を返す
*
* @param k インデックス
* @param f 作用素
* @return PersistentLazySegTree 新しい版 (自身は変わらない)
*/
PersistentLazySegTree apply(long long k, const F& f) const {
assert(0 <= k && k < n);
return apply(k, k + 1, f);
}
/**
* @brief [l, r)の区間の値にfを作用させた新しい版を返す
*
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @param f 作用素
* @return PersistentLazySegTree 新しい版 (自身は変わらない)
*/
PersistentLazySegTree apply(long long l, long long r, const F& f) const {
assert(0 <= l && l <= r && r <= n);
if (l == r) return *this;
return PersistentLazySegTree(pool, n, sz, apply_rec(root, 0, sz, l, r, f));
}
/**
* @brief [l, r)の区間を別の版の値にした新しい版を返す
*
* @param other 写す元の版 (自身と同じ木から作ったもの)
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @return PersistentLazySegTree 新しい版 (自身も other も変わらない)
*/
PersistentLazySegTree copy(const PersistentLazySegTree& other, long long l, long long r) const {
assert(pool == other.pool);
assert(0 <= l && l <= r && r <= n);
if (l == r) return *this;
return PersistentLazySegTree(pool, n, sz, copy_rec(root, other.root, 0, sz, l, r, id()));
}
/**
* @brief (r = l or g(prod([l, r))) = true) and (r = n or g(prod([l, r+1))) = false)となるrを返す
* gが単調なら、g(prod([l, r))) = trueとなる最大のr
*
* @tparam G
* @param l 半開区間の開始 0<=l<=n
* @param g 判定関数 g(e) = true
* @return long long
*/
template <typename G>
long long max_right(long long l, G g) const {
assert(g(e()));
assert(0 <= l && l <= n);
if (l == n) return n;
S sum = e();
long long r = max_right_rec(root, 0, sz, l, g, sum, id());
return r < n ? r : n;
}
/**
* @brief (l = 0 or g(prod([l, r))) = true) and (l = r or g(prod([l-1, r))) = false)となるlを返す
* gが単調なら、g(prod([l, r))) = trueとなる最小のl
*
* @tparam G
* @param r 半開区間の終端 0<=r<=n
* @param g 判定関数 g(e) = true
* @return long long
*/
template <typename G>
long long min_left(long long r, G g) const {
assert(g(e()));
assert(0 <= r && r <= n);
if (r == 0) return 0;
S sum = e();
return min_left_rec(root, 0, sz, r, g, sum, id());
}
/**
* @brief すべての要素を並べた列を返す
*/
std::vector<S> to_vector() const {
std::vector<S> res(n);
for (long long i = 0; i < n; i++) res[i] = get(i);
return res;
}
};
template <typename A>
PersistentLazySegTree(long long, A) -> PersistentLazySegTree<A>;
template <class R, typename A>
PersistentLazySegTree(R&&, A) -> PersistentLazySegTree<A>;
template <typename A>
PersistentLazySegTree(std::initializer_list<typename A::S>, A) -> PersistentLazySegTree<A>;
#line 2 "src/data_structures/persistent-segtree.hpp"
/**
* @file persistent-segtree.hpp
* @brief 永続セグメント木
*/
#line 15 "src/data_structures/persistent-segtree.hpp"
#line 18 "src/data_structures/persistent-segtree.hpp"
/**
* @brief 永続セグメント木
*
* 更新すると新しい版を返し、元の版は変わらない。同じ木から作った版はノードを共有する
* 例:
* PersistentSegTree<monoid::Sum<long long>> s0(n);
* auto s1 = s0.set(3, 10); // s0 はそのまま
* s1.prod(0, 5); // 10
*
* @tparam M モノイド (algebra/monoid.hpp)
*/
template <typename M>
class PersistentSegTree {
public:
using S = typename M::S;
private:
// すべての版のノードを持つ。ノードは削除しない
struct Pool {
M m;
std::vector<S> val;
std::vector<int> left, right; // 葉では -1
explicit Pool(M m) : m(std::move(m)) {}
int make_leaf(const S& x) {
val.push_back(x);
left.push_back(-1);
right.push_back(-1);
return static_cast<int>(val.size()) - 1;
}
int make_node(int l, int r) {
val.push_back(m.op(val[l], val[r]));
left.push_back(l);
right.push_back(r);
return static_cast<int>(val.size()) - 1;
}
};
std::shared_ptr<Pool> pool;
long long n, sz;
int root;
S op(const S& a, const S& b) const { return pool->m.op(a, b); }
S e() const { return pool->m.e(); }
PersistentSegTree(std::shared_ptr<Pool> pool, long long n, long long sz, int root) : pool(std::move(pool)), n(n), sz(sz), root(root) {}
void init_size() {
sz = 1;
while (sz < n) sz <<= 1;
}
template <class It>
int build(It& it, long long a, long long b) {
if (b - a == 1) {
if (a >= n) return pool->make_leaf(e());
S x(*it);
++it;
return pool->make_leaf(x);
}
long long mid = (a + b) / 2;
int l = build(it, a, mid);
int r = build(it, mid, b);
return pool->make_node(l, r);
}
int set_rec(int t, long long a, long long b, long long k, const S& x) const {
if (b - a == 1) return pool->make_leaf(x);
long long mid = (a + b) / 2;
int l = pool->left[t], r = pool->right[t];
if (k < mid)
l = set_rec(l, a, mid, k, x);
else
r = set_rec(r, mid, b, k, x);
return pool->make_node(l, r);
}
// t の [l, r) を u に置き換える
int copy_rec(int t, int u, long long a, long long b, long long l, long long r) const {
if (r <= a || b <= l) return t;
if (l <= a && b <= r) return u;
long long mid = (a + b) / 2;
int lc = copy_rec(pool->left[t], pool->left[u], a, mid, l, r);
int rc = copy_rec(pool->right[t], pool->right[u], mid, b, l, r);
return pool->make_node(lc, rc);
}
S prod_rec(int t, long long a, long long b, long long l, long long r) const {
if (r <= a || b <= l) return e();
if (l <= a && b <= r) return pool->val[t];
long long mid = (a + b) / 2;
return op(prod_rec(pool->left[t], a, mid, l, r), prod_rec(pool->right[t], mid, b, l, r));
}
// [a, b) のうち l 以降で、sum に掛けると f が偽になる最初の位置 (なければ b)
template <typename F>
long long max_right_rec(int t, long long a, long long b, long long l, F& f, S& sum) const {
if (b <= l) return b;
if (l <= a) {
S s = op(sum, pool->val[t]);
if (f(s)) {
sum = s;
return b;
}
if (b - a == 1) return a;
}
long long mid = (a + b) / 2;
long long x = max_right_rec(pool->left[t], a, mid, l, f, sum);
if (x < mid) return x;
return max_right_rec(pool->right[t], mid, b, l, f, sum);
}
// [a, b) のうち r より前で、sum に左から掛けると f が偽になる最後の位置 + 1 (なければ a)
template <typename F>
long long min_left_rec(int t, long long a, long long b, long long r, F& f, S& sum) const {
if (r <= a) return a;
if (b <= r) {
S s = op(pool->val[t], sum);
if (f(s)) {
sum = s;
return a;
}
if (b - a == 1) return b;
}
long long mid = (a + b) / 2;
long long x = min_left_rec(pool->right[t], mid, b, r, f, sum);
if (x > mid) return x;
return min_left_rec(pool->left[t], a, mid, r, f, sum);
}
public:
/**
* @brief コンストラクタ
*
* すべての要素を単位元で初期化する。単位元の部分木は共有するので、n が大きくても O(log n) で作れる
*
* @param n 要素数
* @param m モノイド
*/
explicit PersistentSegTree(long long n = 0, M m = M()) : pool(std::make_shared<Pool>(std::move(m))), n(n) {
assert(0 <= n);
init_size();
root = pool->make_leaf(e());
for (long long w = 1; w < sz; w <<= 1) root = pool->make_node(root, root);
}
/**
* @brief コンストラクタ
*
* @param v 初期の要素
* @param m モノイド
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit PersistentSegTree(R&& v, M m = M()) : pool(std::make_shared<Pool>(std::move(m))), n(internal_traits::range_size(v)) {
init_size();
auto it = internal_traits::range_begin(v);
root = build(it, 0, sz);
}
/**
* @brief 要素数を返す
*/
long long size() const { return n; }
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S get(long long k) const {
assert(0 <= k && k < n);
int t = root;
long long a = 0, b = sz;
while (b - a > 1) {
long long mid = (a + b) / 2;
if (k < mid) {
t = pool->left[t];
b = mid;
} else {
t = pool->right[t];
a = mid;
}
}
return pool->val[t];
}
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S operator[](long long k) const { return get(k); }
/**
* @brief 内容を出力する
*
* @tparam CharT 出力ストリームの文字型
* @tparam Traits 出力ストリームの文字型特性
* @param os 出力ストリーム
* @param rhs 永続セグメント木
* @return std::basic_ostream<CharT, Traits>& 出力ストリーム
*/
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const PersistentSegTree& rhs) {
for (long long i = 0; i < rhs.n; i++) {
if (i != 0) os << CharT(' ');
os << rhs[i];
}
return os;
}
/**
* @brief 指定された要素の値をxにした新しい版を返す
*
* @param k インデックス
* @param x 新しい値
* @return PersistentSegTree 新しい版 (自身は変わらない)
*/
PersistentSegTree set(long long k, const S& x) const {
assert(0 <= k && k < n);
return PersistentSegTree(pool, n, sz, set_rec(root, 0, sz, k, x));
}
/**
* @brief 指定された要素の値にxを作用させた新しい版を返す
*
* @param k インデックス
* @param x 作用素
* @return PersistentSegTree 新しい版 (自身は変わらない)
*/
PersistentSegTree apply(long long k, const S& x) const { return set(k, op(get(k), x)); }
/**
* @brief [l, r)の区間を別の版の値にした新しい版を返す
*
* @param other 写す元の版 (自身と同じ木から作ったもの)
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @return PersistentSegTree 新しい版 (自身も other も変わらない)
*/
PersistentSegTree copy(const PersistentSegTree& other, long long l, long long r) const {
assert(pool == other.pool);
assert(0 <= l && l <= r && r <= n);
if (l == r) return *this;
return PersistentSegTree(pool, n, sz, copy_rec(root, other.root, 0, sz, l, r));
}
/**
* @brief [l, r)の区間の総積を返す
*
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @return S 総積
*/
S prod(long long l, long long r) const {
assert(0 <= l && l <= r && r <= n);
return prod_rec(root, 0, sz, l, r);
}
/**
* @brief すべての要素の総積を返す
*
* @return S 総積
*/
S all_prod() const { return pool->val[root]; }
/**
* @brief (r = l or f(prod([l, r))) = true) and (r = n or f(prod([l, r+1))) = false)となるrを返す
* fが単調なら、f(prod([l, r))) = trueとなる最大のr
*
* @tparam F
* @param l 半開区間の開始 0<=l<=n
* @param f 判定関数 f(e) = true
* @return long long
*/
template <typename F>
long long max_right(long long l, F f) const {
assert(f(e()));
assert(0 <= l && l <= n);
if (l == n) return n;
S sum = e();
long long r = max_right_rec(root, 0, sz, l, f, sum);
return r < n ? r : n;
}
/**
* @brief (l = 0 or f(prod([l, r))) = true) and (l = r or f(prod([l-1, r))) = false)となるlを返す
* fが単調なら、f(prod([l, r))) = trueとなる最小のl
*
* @tparam F
* @param r 半開区間の終端 0<=r<=n
* @param f 判定関数 f(e) = true
* @return long long
*/
template <typename F>
long long min_left(long long r, F f) const {
assert(f(e()));
assert(0 <= r && r <= n);
if (r == 0) return 0;
S sum = e();
return min_left_rec(root, 0, sz, r, f, sum);
}
/**
* @brief すべての要素を並べた列を返す
*/
std::vector<S> to_vector() const {
std::vector<S> res(n);
for (long long i = 0; i < n; i++) res[i] = get(i);
return res;
}
};
template <typename M>
PersistentSegTree(long long, M) -> PersistentSegTree<M>;
template <class R, typename M>
PersistentSegTree(R&&, M) -> PersistentSegTree<M>;
template <typename M>
PersistentSegTree(std::initializer_list<typename M::S>, M) -> PersistentSegTree<M>;
#line 2 "src/data_structures/potentialized-unionfind.hpp"
/**
* @file potentialized-unionfind.hpp
* @brief ポテンシャル付きUnionFind
*/
#line 8 "src/data_structures/potentialized-unionfind.hpp"
#include <stack>
#line 11 "src/data_structures/potentialized-unionfind.hpp"
#line 14 "src/data_structures/potentialized-unionfind.hpp"
/**
* @brief ポテンシャル付きUnionFind
* @tparam G ポテンシャルの群 (algebra/group.hpp) 非可換でもよい
*/
template <typename G>
class PotentializedUnionFind {
public:
using S = typename G::S;
using MergeResult = UnionFind::MergeResult;
private:
G g;
long long _n;
// 負ならサイズ、非負なら親 (メモリを抑えるため int で持つ)
std::vector<int> parent_or_size;
// 重み
std::vector<S> diff_weight;
S op(const S& a, const S& b) const { return g.op(a, b); }
S e() const { return g.e(); }
S inv(const S& a) const { return g.inv(a); }
public:
/**
* @param n 要素数
* @param g ポテンシャルの群
*/
explicit PotentializedUnionFind(long long n = 0, G g = G()) : g(std::move(g)), _n(n), parent_or_size(n, -1), diff_weight(n, e()) {}
/**
* @brief 頂点aの属する連結成分の代表元
*/
long long leader(long long a) {
assert(0 <= a && a < _n);
if (parent_or_size[a] < 0) return a;
std::stack<int> stk;
stk.push(static_cast<int>(a));
while (parent_or_size[stk.top()] >= 0) {
stk.push(parent_or_size[stk.top()]);
}
const int root = stk.top();
stk.pop();
stk.pop();
while (!stk.empty()) {
diff_weight[stk.top()] = op(diff_weight[parent_or_size[stk.top()]], diff_weight[stk.top()]);
parent_or_size[stk.top()] = root;
stk.pop();
}
return root;
}
/**
* @brief a のグループと b のグループを統合する
* @param w (b のポテンシャル) - (a のポテンシャル)
* @return 統合後の代表元と、新しく統合したか
* @note すでに同じ連結成分なら何もしない (w が矛盾していても検出しない)。
* 矛盾を調べるには、merged が false のときに diff(a, b) == w かを確かめる
*/
MergeResult merge(long long a, long long b, S w) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
w = op(weight(a), w);
w = op(w, inv(weight(b)));
long long x = leader(a), y = leader(b);
if (x == y) return {x, false};
if (-parent_or_size[x] < -parent_or_size[y]) {
std::swap(x, y);
w = inv(w);
}
parent_or_size[x] += parent_or_size[y];
parent_or_size[y] = static_cast<int>(x);
diff_weight[y] = w;
return {x, true};
}
/**
* @brief 頂点a,bが連結かどうか
*/
bool same(long long a, long long b) {
assert(0 <= a && a < _n);
assert(0 <= b && b < _n);
return leader(a) == leader(b);
}
/**
* @brief (b のポテンシャル) - (a のポテンシャル)
*/
S diff(long long a, long long b) {
assert(same(a, b));
return op(inv(weight(a)), weight(b));
}
/**
* @brief 頂点aの属する連結成分のサイズ
*/
long long size(long long a) {
assert(0 <= a && a < _n);
return -parent_or_size[leader(a)];
}
/**
* @brief グラフを連結成分に分け、その情報を返す
* @return 「一つの連結成分の頂点番号のリスト」のリスト
*/
std::vector<std::vector<long long>> groups() {
return internal_unionfind::groups(_n, [&](long long a) { return leader(a); });
}
private:
S weight(long long a) {
leader(a);
return diff_weight[a];
}
};
template <typename G>
PotentializedUnionFind(long long, G) -> PotentializedUnionFind<G>;
#line 2 "src/data_structures/priority_counter.hpp"
/**
* @file priority_counter.hpp
* @brief 上位 K 個の値とその個数
*/
#line 14 "src/data_structures/priority_counter.hpp"
#line 16 "src/data_structures/priority_counter.hpp"
template <typename T, std::size_t K = 1, class Compare = std::less<T>, ENABLE_IF_T(K >= 1)>
struct PriorityCounter {
using key_type = T;
using mapped_type = long long;
using value_type = std::pair<key_type, mapped_type>;
inline constexpr static std::size_t k = K;
private:
// C++17 の constexpr コンストラクタではすべてのメンバの初期化が必要なので、値初期化しておく
std::array<value_type, K> data{};
public:
/** @brief 上位から i 番目の値と個数。size() <= i < K では個数は 0 */
constexpr const value_type& operator[](long long i) const {
assert(0 <= i && i < static_cast<long long>(K));
return data[i];
}
constexpr PriorityCounter() {}
explicit constexpr PriorityCounter(const key_type& x) : PriorityCounter() {
data[0].first = x;
data[0].second = 1;
}
constexpr long long size() const {
for (std::size_t i = 0; i < k; i++) {
if (data[i].second == 0) {
return static_cast<long long>(i);
}
}
return k;
}
/** @brief 保持している上位 K 種類の個数の総和 O(K) */
constexpr mapped_type total() const {
mapped_type result = 0;
for (const auto& entry : data) result += entry.second;
return result;
}
constexpr void inc(const key_type& x, const mapped_type& c = 1) {
assert(c > 0);
bool f = false;
key_type pre_key{};
mapped_type pre_mapped{};
for (std::size_t i = 0; i < k; i++) {
if (f) {
// std::swap は C++17 では constexpr でないので手で入れ替える
key_type tmp_key = data[i].first;
data[i].first = pre_key;
pre_key = tmp_key;
mapped_type tmp_mapped = data[i].second;
data[i].second = pre_mapped;
pre_mapped = tmp_mapped;
continue;
}
if (data[i].second == 0) {
data[i].first = x;
data[i].second += c;
return;
}
if (Compare()(data[i].first, x)) {
pre_key = data[i].first;
pre_mapped = data[i].second;
data[i].first = x;
data[i].second = c;
f = true;
} else if (!Compare()(x, data[i].first)) {
data[i].second += c;
return;
}
}
}
constexpr PriorityCounter& operator+=(const PriorityCounter& o) {
for (std::size_t i = 0; i < k; i++) {
if (o.data[i].second == 0) break;
this->inc(o.data[i].first, o.data[i].second);
}
return *this;
}
constexpr friend PriorityCounter operator+(const PriorityCounter& a, const PriorityCounter& b) {
PriorityCounter res(a);
return res += b;
}
};
template <typename T, std::size_t K = 1>
using MaxCounter = PriorityCounter<T, K>;
template <typename T, std::size_t K = 1>
using MinCounter = PriorityCounter<T, K, std::greater<T>>;
#line 2 "src/data_structures/rbst.hpp"
/**
* @file rbst.hpp
* @brief 平衡二分木 (RBST) による列
*/
#line 10 "src/data_structures/rbst.hpp"
#include <cstdint>
#line 16 "src/data_structures/rbst.hpp"
#line 19 "src/data_structures/rbst.hpp"
namespace internal_rbst {
#if __cplusplus < 202002L
template <typename M, typename = void>
struct has_acted : std::false_type {};
template <typename M>
struct has_acted<M, std::void_t<typename M::F>> : std::true_type {};
#endif
// 作用素付きでないモノイドのときの作用素の型
struct NoAct {
using F = NoAct;
};
} // namespace internal_rbst
/**
* @brief 平衡二分木 (RBST) による列
*
* 位置で扱う列。k 番目への挿入・削除、区間積、区間反転、split・merge を期待 O(log n) で行う
* モノイド (algebra/monoid.hpp) か作用素付きモノイド (algebra/acted-monoid.hpp) を乗せる。作用素付きなら区間作用もできる
* 作用素付きモノイドの mapping は (f, x) か (f, x, sz) の形にする (列の位置は挿入・削除で変わるので (f, x, l, r) は使えない)
* 頂点は型ごとに共有する配列に置くので、同じ型の木どうしで split・merge できる
* 例:
* RBST<acted_monoid::AddSum<long long>> t(v);
* t.insert(2, x); t.erase(0); t.reverse(1, 4); t.apply(0, 3, 10); t.prod(1, 3);
* RBST<acted_monoid::AddSum<long long>> u = t.split(2); // t は先頭 2 個、u は残り
* t.merge(std::move(u)); // 元に戻す
*
* @tparam M モノイドか作用素付きモノイド
*/
template <typename M>
class RBST {
public:
using S = typename M::S;
#if __cplusplus >= 202002L
static constexpr bool acted = requires { typename M::F; };
#else
static constexpr bool acted = internal_rbst::has_acted<M>::value;
#endif
using F = typename std::conditional_t<acted, M, internal_rbst::NoAct>::F;
private:
#if __cplusplus >= 202002L
static_assert(!acted || !requires(const M& m, const F& f, const S& x) { m.mapping(f, x, 0LL, 0LL); }, "RBST: mapping(f, x, l, r) は使えない");
#else
static_assert(!acted || !internal_acted_monoid::has_mapping_lr<M>::value, "RBST: mapping(f, x, l, r) は使えない");
#endif
// 頂点 0 は空の木を表す
struct Node {
S val, sum, rsum; // 値、部分木の積、部分木の逆順の積
F lz; // 子に伝える作用素
int sz = 0, l = 0, r = 0;
bool has_lz = false, rev = false; // 子に作用素・反転を伝えていないか
};
// 頂点の配列は最初に頂点を作るときに確保し、解放しない
// (グローバル変数の木のデストラクタが、先に破棄された配列を触らないようにする)
inline static std::vector<Node>* nodes_ = nullptr;
inline static std::vector<int>* unused_ = nullptr; // 消した頂点
static Node& node(int t) { return (*nodes_)[t]; }
static std::uint32_t rand() {
static std::uint32_t x = 2463534242U;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
return x;
}
M m;
int root = 0;
S op(const S& x, const S& y) const { return m.op(x, y); }
S e() const { return m.e(); }
static int size_of(int t) { return t ? node(t).sz : 0; }
S sum_of(int t) const { return t ? node(t).sum : e(); }
S rsum_of(int t) const { return t ? node(t).rsum : e(); }
// x は値で受け取る (頂点の配列の要素を渡されたとき、配列が伸びて参照が無効になるのを防ぐ)
int new_node(S x) {
if (!nodes_) nodes_ = new std::vector<Node>(1), unused_ = new std::vector<int>();
int t;
if (!unused_->empty()) {
t = unused_->back();
unused_->pop_back();
} else {
t = nodes_->size();
nodes_->emplace_back();
}
Node& v = node(t);
v.val = v.sum = v.rsum = x;
v.has_lz = v.rev = false;
v.sz = 1, v.l = v.r = 0;
return t;
}
// 部分木の頂点をすべて消す
static void free_tree(int t) {
if (!t) return;
std::vector<int> st = {t};
while (!st.empty()) {
int v = st.back();
st.pop_back();
if (node(v).l) st.push_back(node(v).l);
if (node(v).r) st.push_back(node(v).r);
unused_->push_back(v);
}
}
int clone_tree(int t) {
if (!t) return 0;
push(t);
int lc = clone_tree(node(t).l);
int c = new_node(node(t).val);
int rc = clone_tree(node(t).r);
node(c).l = lc, node(c).r = rc;
update(c);
return c;
}
void update(int t) {
Node& v = node(t);
v.sz = node(v.l).sz + node(v.r).sz + 1;
v.sum = op(op(sum_of(v.l), v.val), sum_of(v.r));
v.rsum = op(op(rsum_of(v.r), v.val), rsum_of(v.l));
}
void all_apply(int t, const F& f) {
if (!t) return;
if constexpr (acted) {
Node& v = node(t);
v.val = acted_monoid::apply_mapping(m, f, v.val, 0, 1);
v.sum = acted_monoid::apply_mapping(m, f, v.sum, 0, v.sz);
v.rsum = acted_monoid::apply_mapping(m, f, v.rsum, 0, v.sz);
v.lz = v.has_lz ? m.composition(f, v.lz) : f;
v.has_lz = true;
}
}
static void toggle(int t) {
if (!t) return;
Node& v = node(t);
std::swap(v.l, v.r);
std::swap(v.sum, v.rsum);
v.rev = !v.rev;
}
void push(int t) {
Node& v = node(t);
if (v.rev) {
toggle(v.l), toggle(v.r);
v.rev = false;
}
if constexpr (acted) {
if (v.has_lz) {
all_apply(v.l, v.lz), all_apply(v.r, v.lz);
v.has_lz = false;
}
}
}
int merge_node(int a, int b) {
if (!a || !b) return a ^ b;
// 大きさに比例する確率で根を選ぶ ([0, 大きさの和) の乱数を、割り算の代わりに掛け算とシフトで作る)
if ((static_cast<std::uint64_t>(rand()) * (static_cast<std::uint64_t>(node(a).sz) + node(b).sz) >> 32) < static_cast<std::uint64_t>(node(a).sz)) {
push(a);
int c = merge_node(node(a).r, b);
node(a).r = c;
update(a);
return a;
}
push(b);
int c = merge_node(a, node(b).l);
node(b).l = c;
update(b);
return b;
}
// 先頭 k 個と残りに分ける
std::pair<int, int> split_node(int t, int k) {
if (!t) return {0, 0};
push(t);
int ls = node(node(t).l).sz;
if (k <= ls) {
auto [a, b] = split_node(node(t).l, k);
node(t).l = b;
update(t);
return {a, t};
}
auto [a, b] = split_node(node(t).r, k - ls - 1);
node(t).r = a;
update(t);
return {t, b};
}
template <class It>
int build(It& it, int lo, int hi) {
if (lo >= hi) return 0;
int mid = (lo + hi) / 2;
int lc = build(it, lo, mid);
int t = new_node(S(*it));
++it;
int rc = build(it, mid + 1, hi);
node(t).l = lc, node(t).r = rc;
update(t);
return t;
}
// [l, r) を取り出して f を作用させ、元に戻す
template <typename Fn>
auto with_range(long long l, long long r, Fn fn) {
assert(0 <= l && l <= r && r <= size());
auto [a, bc] = split_node(root, static_cast<int>(l));
auto [b, c] = split_node(bc, static_cast<int>(r - l));
if constexpr (std::is_void_v<decltype(fn(b))>) {
fn(b);
root = merge_node(merge_node(a, b), c);
} else {
auto res = fn(b);
root = merge_node(merge_node(a, b), c);
return res;
}
}
void to_vector(int t, std::vector<S>& res) {
if (!t) return;
push(t);
to_vector(node(t).l, res);
res.push_back(node(t).val);
to_vector(node(t).r, res);
}
class RBSTReference {
RBST& t;
long long k;
public:
RBSTReference(RBST& t, long long k) : t(t), k(k) {}
RBSTReference& operator=(const S& x) {
t.set(k, x);
return *this;
}
operator S() { return t.get(k); }
};
struct FromRoot {};
RBST(int root, const M& m, FromRoot) : m(m), root(root) {}
public:
/**
* @brief 空の列
*/
explicit RBST(M m = M()) : m(std::move(m)) {}
/**
* @brief 長さ n で、すべて単位元の列
*/
explicit RBST(long long n, M m = M()) : RBST(std::vector<S>(n, m.e()), m) {}
/**
* @brief v の列 O(n)
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit RBST(R&& v, M m = M()) : m(std::move(m)) {
auto it = internal_traits::range_begin(v);
root = build(it, 0, static_cast<int>(internal_traits::range_size(v)));
}
/**
* @brief 複製する O(n)
*/
RBST(const RBST& o) : m(o.m) { root = const_cast<RBST&>(o).clone_tree(o.root); }
RBST(RBST&& o) noexcept : m(std::move(o.m)), root(o.root) { o.root = 0; }
RBST& operator=(const RBST& o) {
if (this != &o) {
int c = const_cast<RBST&>(o).clone_tree(o.root);
free_tree(root);
m = o.m, root = c;
}
return *this;
}
RBST& operator=(RBST&& o) noexcept {
if (this != &o) {
free_tree(root);
m = std::move(o.m), root = o.root;
o.root = 0;
}
return *this;
}
~RBST() { free_tree(root); }
/**
* @brief 列の長さ
*/
long long size() const { return size_of(root); }
/**
* @brief 空か
*/
bool empty() const { return root == 0; }
/**
* @brief k 番目の値
*/
S get(long long k) {
assert(0 <= k && k < size());
int t = root;
while (true) {
push(t);
int ls = node(node(t).l).sz;
if (k < ls) {
t = node(t).l;
} else if (k == ls) {
return node(t).val;
} else {
k -= ls + 1;
t = node(t).r;
}
}
}
/**
* @brief k 番目の要素への参照 (代入すると set が呼ばれる)
*/
RBSTReference operator[](long long k) { return RBSTReference(*this, k); }
/**
* @brief k 番目の値を x にする
*/
void set(long long k, const S& x) {
assert(0 <= k && k < size());
with_range(k, k + 1, [&](int t) { node(t).val = node(t).sum = node(t).rsum = x; });
}
/**
* @brief k 番目 (0 <= k <= size()) に x を挿入する。後ろの要素は 1 つずつずれる
*/
void insert(long long k, const S& x) {
assert(0 <= k && k <= size());
auto [a, b] = split_node(root, static_cast<int>(k));
root = merge_node(merge_node(a, new_node(x)), b);
}
void push_front(const S& x) { insert(0, x); }
void push_back(const S& x) { insert(size(), x); }
/**
* @brief k 番目を削除して、その値を返す
*/
S erase(long long k) {
assert(0 <= k && k < size());
auto [a, bc] = split_node(root, static_cast<int>(k));
auto [b, c] = split_node(bc, 1);
S x = node(b).val;
free_tree(b);
root = merge_node(a, c);
return x;
}
S pop_front() { return erase(0); }
S pop_back() { return erase(size() - 1); }
/**
* @brief [l, r) の積
*/
S prod(long long l, long long r) {
return with_range(l, r, [&](int t) { return sum_of(t); });
}
/**
* @brief 列全体の積 O(1)
*/
S all_prod() const { return sum_of(root); }
/**
* @brief [l, r) を反転する
*/
void reverse(long long l, long long r) {
with_range(l, r, [&](int t) { toggle(t); });
}
/**
* @brief [l, r) の各値に f を作用させる (作用素付きモノイドのとき)
*/
template <bool B = acted, std::enable_if_t<B, std::nullptr_t> = nullptr>
void apply(long long l, long long r, const F& f) {
with_range(l, r, [&](int t) { all_apply(t, f); });
}
/**
* @brief k 番目の値に f を作用させる (作用素付きモノイドのとき)
*/
template <bool B = acted, std::enable_if_t<B, std::nullptr_t> = nullptr>
void apply(long long k, const F& f) {
assert(0 <= k && k < size());
apply(k, k + 1, f);
}
/**
* @brief 末尾に other をつなげる。other は空になる
*/
void merge(RBST&& other) {
root = merge_node(root, other.root);
other.root = 0;
}
/**
* @brief 先頭 k 個を残し、残りを切り取って返す
*/
RBST split(long long k) {
assert(0 <= k && k <= size());
auto [a, b] = split_node(root, static_cast<int>(k));
root = a;
return RBST(b, m, FromRoot{});
}
/**
* @brief g(prod(l, r)) が true となる最大の r (g(e()) は true であること)
* g が単調なら、g(prod(l, r)) が true となる r は l から始まる区間をなす
*/
template <typename G>
long long max_right(long long l, G g) {
assert(0 <= l && l <= size());
assert(g(e()));
auto [a, b] = split_node(root, static_cast<int>(l));
long long res = l;
S acc = e();
int t = b;
while (t) {
push(t);
S s = op(acc, sum_of(node(t).l));
if (!g(s)) {
t = node(t).l;
continue;
}
S s2 = op(s, node(t).val);
if (!g(s2)) {
res += node(node(t).l).sz;
break;
}
acc = s2;
res += node(node(t).l).sz + 1;
t = node(t).r;
}
root = merge_node(a, b);
return res;
}
/**
* @brief g(prod(l, r)) が true となる最小の l (g(e()) は true であること)
*/
template <typename G>
long long min_left(long long r, G g) {
assert(0 <= r && r <= size());
assert(g(e()));
auto [a, b] = split_node(root, static_cast<int>(r));
long long res = r;
S acc = e();
int t = a;
while (t) {
push(t);
S s = op(sum_of(node(t).r), acc);
if (!g(s)) {
t = node(t).r;
continue;
}
S s2 = op(node(t).val, s);
if (!g(s2)) {
res -= node(node(t).r).sz;
break;
}
acc = s2;
res -= node(node(t).r).sz + 1;
t = node(t).l;
}
root = merge_node(a, b);
return res;
}
/**
* @brief 列を std::vector にする O(n)
*/
std::vector<S> to_vector() {
std::vector<S> res;
res.reserve(size());
to_vector(root, res);
return res;
}
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, RBST& t) {
std::vector<S> v = t.to_vector();
for (int i = 0; i < static_cast<int>(v.size()); i++) {
if (i != 0) os << CharT(' ');
os << v[i];
}
return os;
}
};
template <class R, typename M>
RBST(R&&, M) -> RBST<M>;
template <typename M>
RBST(std::initializer_list<typename M::S>, M) -> RBST<M>;
#line 2 "src/data_structures/segtree-beats.hpp"
/**
* @file segtree-beats.hpp
* @brief Segment Tree Beats
*/
#line 12 "src/data_structures/segtree-beats.hpp"
#include <tuple>
#line 16 "src/data_structures/segtree-beats.hpp"
#line 2 "src/algebra/beats-acted-monoid.hpp"
/**
* @file beats-acted-monoid.hpp
* @brief Segment Tree Beats 用の作用素付きモノイド
*
* 作用素付きモノイド (algebra/acted-monoid.hpp) と同じメンバを持つが、
* mapping は std::pair<bool, S> (作用に失敗したか, 作用後の値) を返す
* data_structures/segtree-beats.hpp に渡して使う
*/
#line 20 "src/algebra/beats-acted-monoid.hpp"
#line 22 "src/algebra/beats-acted-monoid.hpp"
namespace beats_acted_monoid {
/**
* @brief 区間 chmin、区間和・最大値
*
* 作用素は chmin する値 (x <- min(x, f))
* S(x) で値 x の1要素から作り、sum, max1 で区間和・最大値を取得する
* 空の区間では max1 = numeric_limits<T>::lowest()
* ChminChmaxAddSum より軽い
*
* @tparam T 値の型
*/
template <typename T>
struct ChminSum {
static constexpr T lowest = std::numeric_limits<T>::lowest();
struct S {
T sum;
T max1, max2; // 最大値、2番目の最大値 (なければ lowest)
long long max_cnt; // 最大値の個数
constexpr S() : sum(0), max1(lowest), max2(lowest), max_cnt(0) {}
constexpr S(const T& x) : sum(x), max1(x), max2(lowest), max_cnt(1) {}
};
using F = T;
static constexpr S op(const S& a, const S& b) {
S res;
res.sum = a.sum + b.sum;
if (a.max1 == b.max1) {
res.max1 = a.max1;
res.max_cnt = a.max_cnt + b.max_cnt;
res.max2 = std::max(a.max2, b.max2);
} else if (a.max1 > b.max1) {
res.max1 = a.max1;
res.max_cnt = a.max_cnt;
res.max2 = std::max(a.max2, b.max1);
} else {
res.max1 = b.max1;
res.max_cnt = b.max_cnt;
res.max2 = std::max(a.max1, b.max2);
}
return res;
}
static constexpr S e() { return S(); }
static constexpr std::pair<bool, S> mapping(const F& f, const S& x) {
if (x.max1 <= f) return {false, x};
// 最大値だけが変わる (値が 1 種類なら f = lowest でも成功させる)
if (x.max2 < f || x.max2 == lowest) {
S res = x;
res.sum -= (x.max1 - f) * T(x.max_cnt);
res.max1 = f;
return {false, res};
}
return {true, x};
}
static constexpr F composition(const F& f, const F& g) { return std::min(f, g); }
static constexpr F id() { return std::numeric_limits<T>::max(); }
};
/**
* @brief 区間 chmax、区間和・最小値
*
* 作用素は chmax する値 (x <- max(x, f))
* S(x) で値 x の1要素から作り、sum, min1 で区間和・最小値を取得する
* 空の区間では min1 = numeric_limits<T>::max()
* ChminChmaxAddSum より軽い
*
* @tparam T 値の型
*/
template <typename T>
struct ChmaxSum {
static constexpr T highest = std::numeric_limits<T>::max();
struct S {
T sum;
T min1, min2; // 最小値、2番目の最小値 (なければ highest)
long long min_cnt; // 最小値の個数
constexpr S() : sum(0), min1(highest), min2(highest), min_cnt(0) {}
constexpr S(const T& x) : sum(x), min1(x), min2(highest), min_cnt(1) {}
};
using F = T;
static constexpr S op(const S& a, const S& b) {
S res;
res.sum = a.sum + b.sum;
if (a.min1 == b.min1) {
res.min1 = a.min1;
res.min_cnt = a.min_cnt + b.min_cnt;
res.min2 = std::min(a.min2, b.min2);
} else if (a.min1 < b.min1) {
res.min1 = a.min1;
res.min_cnt = a.min_cnt;
res.min2 = std::min(a.min2, b.min1);
} else {
res.min1 = b.min1;
res.min_cnt = b.min_cnt;
res.min2 = std::min(a.min1, b.min2);
}
return res;
}
static constexpr S e() { return S(); }
static constexpr std::pair<bool, S> mapping(const F& f, const S& x) {
if (x.min1 >= f) return {false, x};
// 最小値だけが変わる (値が 1 種類なら f = highest でも成功させる)
if (x.min2 > f || x.min2 == highest) {
S res = x;
res.sum += (f - x.min1) * T(x.min_cnt);
res.min1 = f;
return {false, res};
}
return {true, x};
}
static constexpr F composition(const F& f, const F& g) { return std::max(f, g); }
static constexpr F id() { return std::numeric_limits<T>::lowest(); }
};
/**
* @brief 区間 chmin・chmax・加算・代入、区間和・最大値・最小値
*
* 作用素 F = ClampAdd<T>{lb, ub, add} は x <- clamp(x + add, lb, ub) を表す (lb <= ub)
* chmin(b), chmax(b), add(b), update(b) で作る
* S(x) で値 x の1要素から作り、sum, max1, min1 で区間和・最大値・最小値を取得する
* 空の区間では max1 = numeric_limits<T>::lowest(), min1 = numeric_limits<T>::max()
*
* @tparam T 値の型 (符号付き整数を想定する)
*/
template <typename T>
struct ChminChmaxAddSum {
static constexpr T lowest = std::numeric_limits<T>::lowest();
static constexpr T highest = std::numeric_limits<T>::max();
struct S {
T sum;
T max1, max2; // 最大値、2番目の最大値 (なければ lowest)
T min1, min2; // 最小値、2番目の最小値 (なければ highest)
long long max_cnt, min_cnt; // 最大値・最小値の個数
constexpr S() : sum(0), max1(lowest), max2(lowest), min1(highest), min2(highest), max_cnt(0), min_cnt(0) {}
constexpr S(const T& x) : sum(x), max1(x), max2(lowest), min1(x), min2(highest), max_cnt(1), min_cnt(1) {}
};
using F = ClampAdd<T>;
static constexpr F chmin(const T& b) { return {lowest, b, T(0)}; }
static constexpr F chmax(const T& b) { return {b, highest, T(0)}; }
static constexpr F add(const T& b) { return {lowest, highest, b}; }
static constexpr F update(const T& b) { return {b, b, T(0)}; }
static constexpr S op(const S& a, const S& b) {
S res;
res.sum = a.sum + b.sum;
if (a.max1 == b.max1) {
res.max1 = a.max1;
res.max_cnt = a.max_cnt + b.max_cnt;
res.max2 = std::max(a.max2, b.max2);
} else if (a.max1 > b.max1) {
res.max1 = a.max1;
res.max_cnt = a.max_cnt;
res.max2 = std::max(a.max2, b.max1);
} else {
res.max1 = b.max1;
res.max_cnt = b.max_cnt;
res.max2 = std::max(a.max1, b.max2);
}
if (a.min1 == b.min1) {
res.min1 = a.min1;
res.min_cnt = a.min_cnt + b.min_cnt;
res.min2 = std::min(a.min2, b.min2);
} else if (a.min1 < b.min1) {
res.min1 = a.min1;
res.min_cnt = a.min_cnt;
res.min2 = std::min(a.min2, b.min1);
} else {
res.min1 = b.min1;
res.min_cnt = b.min_cnt;
res.min2 = std::min(a.min1, b.min2);
}
return res;
}
static constexpr S e() { return S(); }
static constexpr std::pair<bool, S> mapping(const F& f, const S& x, long long sz) {
if (x.max_cnt == 0) return {false, x};
S res = x;
// 加算 (番兵には足さない)
res.sum += f.add * T(sz);
res.max1 += f.add;
res.min1 += f.add;
if (res.max2 != lowest) res.max2 += f.add;
if (res.min2 != highest) res.min2 += f.add;
// 値が 1 種類
if (res.max1 == res.min1) {
T v = std::clamp(res.max1, f.lb, f.ub);
res.max1 = res.min1 = v;
res.sum = v * T(sz);
return {false, res};
}
// 値が 2 種類
if (res.max1 == res.min2) {
T hi = std::clamp(res.max1, f.lb, f.ub), lo = std::clamp(res.min1, f.lb, f.ub);
if (hi == lo) {
res.max1 = res.min1 = hi;
res.max2 = lowest;
res.min2 = highest;
res.max_cnt = res.min_cnt = sz;
res.sum = hi * T(sz);
} else {
res.max1 = res.min2 = hi;
res.min1 = res.max2 = lo;
res.sum = hi * T(res.max_cnt) + lo * T(res.min_cnt);
}
return {false, res};
}
// 値が 3 種類以上: 最大値と最小値だけが変わる場合以外は失敗
if (f.ub <= res.max2 || f.lb >= res.min2) return {true, res};
if (f.ub < res.max1) {
res.sum -= (res.max1 - f.ub) * T(res.max_cnt);
res.max1 = f.ub;
}
if (f.lb > res.min1) {
res.sum += (f.lb - res.min1) * T(res.min_cnt);
res.min1 = f.lb;
}
return {false, res};
}
// g を適用した後に f を適用する
static constexpr F composition(const F& f, const F& g) { return monoid::ClampAddComposite<T>::op(f, g); }
static constexpr F id() { return {lowest, highest, T(0)}; }
};
/**
* @brief 区間 chmin・chmax・加算・代入、0 乗和から K 乗和
* @tparam T 比較する値の型 (符号付き整数)
* @tparam K 最大次数
* @tparam U 乗和の型 (modint も可)
*/
template <typename T = long long, long long K = 2, typename U = T>
struct ChminChmaxAddPowerSum {
static_assert(K >= 0);
static_assert(std::is_integral_v<T> && std::is_signed_v<T>);
static constexpr T lowest = std::numeric_limits<T>::lowest();
static constexpr T highest = std::numeric_limits<T>::max();
struct S {
std::array<U, K + 1> val{};
T max1 = lowest, max2 = lowest, min1 = highest, min2 = highest;
long long max_cnt = 0, min_cnt = 0;
constexpr S() = default;
constexpr S(const T& x) : max1(x), min1(x), max_cnt(1), min_cnt(1) {
val[0] = U(1);
for (long long i = 1; i <= K; ++i) val[i] = val[i - 1] * U(x);
}
constexpr const U& operator[](long long i) const {
assert(0 <= i && i <= K);
return val[i];
}
};
using F = ClampAdd<T>;
static constexpr F chmin(const T& b) { return {lowest, b, T(0)}; }
static constexpr F chmax(const T& b) { return {b, highest, T(0)}; }
static constexpr F add(const T& b) { return {lowest, highest, b}; }
static constexpr F update(const T& b) { return {b, b, T(0)}; }
static constexpr S op(const S& a, const S& b) {
if (a.max_cnt == 0) return b;
if (b.max_cnt == 0) return a;
S res;
for (long long i = 0; i <= K; ++i) res.val[i] = a.val[i] + b.val[i];
res.max1 = std::max(a.max1, b.max1);
res.max_cnt = (a.max1 == res.max1 ? a.max_cnt : 0) + (b.max1 == res.max1 ? b.max_cnt : 0);
res.max2 = std::max(a.max1 == res.max1 ? a.max2 : a.max1, b.max1 == res.max1 ? b.max2 : b.max1);
res.min1 = std::min(a.min1, b.min1);
res.min_cnt = (a.min1 == res.min1 ? a.min_cnt : 0) + (b.min1 == res.min1 ? b.min_cnt : 0);
res.min2 = std::min(a.min1 == res.min1 ? a.min2 : a.min1, b.min1 == res.min1 ? b.min2 : b.min1);
return res;
}
static constexpr S e() { return S(); }
static std::pair<bool, S> mapping(const F& f, const S& x, long long sz) {
if (x.max_cnt == 0) return {false, x};
// 全要素が同じ値になる場合は、加算や二項展開より先に処理する。
T lo = std::clamp(x.min1 + f.add, f.lb, f.ub);
T hi = std::clamp(x.max1 + f.add, f.lb, f.ub);
if (lo == hi) {
S res(lo);
for (auto& v : res.val) v *= U(sz);
res.max_cnt = res.min_cnt = sz;
return {false, res};
}
S res = x;
res.max1 += f.add;
res.min1 += f.add;
if (res.max2 != lowest) res.max2 += f.add;
if (res.min2 != highest) res.min2 += f.add;
if (res.max1 != res.min2 && (f.ub <= res.max2 || f.lb >= res.min2)) return {true, x};
if (f.add != T(0)) {
static const auto binom = [] {
std::array<std::array<U, K + 1>, K + 1> c{};
for (long long i = 0; i <= K; ++i) {
c[i][0] = c[i][i] = U(1);
for (long long j = 1; j < i; ++j) c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
return c;
}();
std::array<U, K + 1> pw{};
pw[0] = U(1);
for (long long i = 1; i <= K; ++i) pw[i] = pw[i - 1] * U(f.add);
res.val.fill(U(0));
for (long long i = 0; i <= K; ++i)
for (long long j = 0; j <= i; ++j) res.val[i] += binom[i][j] * pw[j] * x.val[i - j];
}
auto replace = [&](T before, T after, long long count) {
U p(1), q(1);
for (long long i = 1; i <= K; ++i) {
p *= U(before);
q *= U(after);
res.val[i] += (q - p) * U(count);
}
};
replace(res.max1, hi, res.max_cnt);
replace(res.min1, lo, res.min_cnt);
if (res.max1 == res.min2) {
res.max2 = lo;
res.min2 = hi;
}
res.max1 = hi;
res.min1 = lo;
return {false, res};
}
static constexpr F composition(const F& f, const F& g) { return monoid::ClampAddComposite<T>::op(f, g); }
static constexpr F id() { return F(); }
};
/** @brief 非負整数への区間 AND・OR、区間最小値・最大値 */
template <typename T = long long>
struct BitwiseAndOrMinMax {
static_assert(std::is_integral_v<T> && !std::is_same_v<T, bool>);
static constexpr T mask = std::numeric_limits<T>::max();
struct S {
T min = mask, max = T(0), bit_and = mask, bit_or = T(0);
long long size = 0;
constexpr S() = default;
constexpr S(T x) : min(x), max(x), bit_and(x), bit_or(x), size(1) { assert(x >= T(0)); }
};
struct F {
T and_mask = mask, or_mask = T(0);
};
static constexpr F bit_and(T b) {
assert(b >= T(0));
return {b, T(0)};
}
static constexpr F bit_or(T b) {
assert(b >= T(0));
return {mask, b};
}
static constexpr S e() { return S(); }
static constexpr S op(const S& a, const S& b) {
if (a.size == 0) return b;
if (b.size == 0) return a;
S res;
res.min = std::min(a.min, b.min);
res.max = std::max(a.max, b.max);
res.bit_and = a.bit_and & b.bit_and;
res.bit_or = a.bit_or | b.bit_or;
res.size = a.size + b.size;
return res;
}
static constexpr std::pair<bool, S> mapping(const F& f, const S& x) {
if (x.size == 0) return {false, x};
T changed = static_cast<T>((mask ^ f.and_mask) | f.or_mask);
if ((changed & (x.bit_and ^ x.bit_or)) != T(0)) return {true, x};
S res = x;
res.min = (res.min & f.and_mask) | f.or_mask;
res.max = (res.max & f.and_mask) | f.or_mask;
res.bit_and = (res.bit_and & f.and_mask) | f.or_mask;
res.bit_or = (res.bit_or & f.and_mask) | f.or_mask;
return {false, res};
}
static constexpr F composition(const F& f, const F& g) {
return {static_cast<T>(g.and_mask & f.and_mask), static_cast<T>((g.or_mask & f.and_mask) | f.or_mask)};
}
static constexpr F id() { return F(); }
};
/** @brief 非負整数への区間整数除算・代入、区間和・最小値・最大値 */
template <typename T = long long, typename U = T>
struct DivUpdateSum {
static_assert(std::is_integral_v<T> && !std::is_same_v<T, bool>);
struct S {
U sum = U(0);
T min = std::numeric_limits<T>::max(), max = T(0);
long long size = 0;
constexpr S() = default;
constexpr S(T x) : sum(U(x)), min(x), max(x), size(1) { assert(x >= T(0)); }
};
struct F {
T divisor = T(1);
std::optional<T> value;
};
static constexpr F div(T d) {
assert(d >= T(1));
return {d, std::nullopt};
}
static constexpr F update(T b) {
assert(b >= T(0));
return {T(1), b};
}
static constexpr S e() { return S(); }
static constexpr S op(const S& a, const S& b) {
S res;
res.sum = a.sum + b.sum;
res.size = a.size + b.size;
res.min = std::min(a.min, b.min);
res.max = std::max(a.max, b.max);
return res;
}
static constexpr std::pair<bool, S> mapping(const F& f, const S& x) {
if (x.size == 0 || (!f.value && f.divisor == T(1))) return {false, x};
T lo = f.value ? *f.value : x.min / f.divisor;
T hi = f.value ? *f.value : x.max / f.divisor;
if (lo != hi) return {true, x};
S res(lo);
res.sum *= U(x.size);
res.size = x.size;
return {false, res};
}
static constexpr F composition(const F& f, const F& g) {
if (f.value) return f;
if (g.value) return update(*g.value / f.divisor);
// 除数の積が値域を超えるなら、どの非負値も 0 になる。
if (g.divisor > std::numeric_limits<T>::max() / f.divisor) return update(T(0));
return div(g.divisor * f.divisor);
}
static constexpr F id() { return F(); }
};
/** @brief 非負整数への区間 gcd・代入、区間和・最小値・最大値 */
template <typename T = long long, typename U = T>
struct GcdUpdateSum {
static_assert(std::is_integral_v<T> && !std::is_same_v<T, bool>);
struct S {
U sum = U(0);
T min = std::numeric_limits<T>::max(), max = T(0), lcm = T(1);
bool lcm_overflow = false;
long long size = 0;
constexpr S() = default;
constexpr S(T x) : sum(U(x)), min(x), max(x), lcm(x), size(1) { assert(x >= T(0)); }
};
struct F {
T factor = T(0);
std::optional<T> value;
};
static constexpr F gcd(T b) {
assert(b >= T(0));
return {b, std::nullopt};
}
static constexpr F update(T b) {
assert(b >= T(0));
return {T(0), b};
}
static constexpr S e() { return S(); }
static constexpr S op(const S& a, const S& b) {
if (a.size == 0) return b;
if (b.size == 0) return a;
S res;
res.sum = a.sum + b.sum;
res.min = std::min(a.min, b.min);
res.max = std::max(a.max, b.max);
res.size = a.size + b.size;
if (res.min == T(0)) {
res.lcm = T(0);
} else if (a.lcm_overflow || b.lcm_overflow) {
res.lcm_overflow = true;
} else {
T v = a.lcm / std::gcd(a.lcm, b.lcm);
if (v > std::numeric_limits<T>::max() / b.lcm)
res.lcm_overflow = true;
else
res.lcm = v * b.lcm;
}
return res;
}
static constexpr std::pair<bool, S> mapping(const F& f, const S& x) {
if (x.size == 0) return {false, x};
if (!f.value) {
if (f.factor == T(0)) return {false, x};
if (x.min > T(0) && !x.lcm_overflow && f.factor % x.lcm == T(0)) return {false, x};
if (x.min != x.max) return {true, x};
}
T value = f.value ? *f.value : std::gcd(x.min, f.factor);
S res(value);
res.sum *= U(x.size);
res.size = x.size;
return {false, res};
}
static constexpr F composition(const F& f, const F& g) {
if (f.value) return f;
if (g.value) return update(std::gcd(*g.value, f.factor));
return gcd(std::gcd(f.factor, g.factor));
}
static constexpr F id() { return F(); }
};
} // namespace beats_acted_monoid
#line 20 "src/data_structures/segtree-beats.hpp"
/**
* @brief Segment Tree Beats
*
* 作用素付きモノイド (algebra/acted-monoid.hpp) と同じ形の型を受け取るが、
* mapping は std::pair<bool, S> (作用に失敗したか, 作用後の値) を返す
* 失敗した場合は子に伝搬してから計算し直す
*
* @tparam A 作用素付きモノイド
*/
template <typename A>
class SegTreeBeats {
public:
using S = typename A::S;
using F = typename A::F;
private:
A a;
S op(const S& x, const S& y) const { return a.op(x, y); }
S e() const { return a.e(); }
std::pair<bool, S> mapping(const F& f, const S& x, long long l, long long r) const { return acted_monoid::apply_mapping(a, f, x, l, r); }
F composition(const F& f, const F& g) const { return a.composition(f, g); }
F id() const { return a.id(); }
long long n, sz;
int height;
std::vector<S> data;
std::vector<int> fail;
std::vector<F> lazy;
void update(long long k) {
data[k] = op(data[2 * k], data[2 * k + 1]);
fail[k] = false;
}
void apply_node(long long k, int h, const F& f) {
// 末尾の要素数を 2 べきにそろえるための余りの部分は区間に含めない
long long l = std::min((k << h) & (sz - 1), n);
long long r = std::min(((k << h) & (sz - 1)) + (1LL << h), n);
std::tie(fail[k], data[k]) = mapping(f, data[k], l, r);
if (k < sz) {
lazy[k] = composition(f, lazy[k]);
if (fail[k]) {
push(k, h);
update(k);
}
}
}
void push(long long k, int h) {
apply_node(2 * k, h - 1, lazy[k]);
apply_node(2 * k + 1, h - 1, lazy[k]);
lazy[k] = id();
}
class SegTreeBeatsReference {
SegTreeBeats& segtree;
long long k;
public:
SegTreeBeatsReference(SegTreeBeats& segtree, long long k) : segtree(segtree), k(k) {}
SegTreeBeatsReference& operator=(const S& x) {
segtree.set(k, x);
return *this;
}
operator S() { return segtree.get(k); }
};
void construct_data() {
sz = 1;
height = 0;
while (sz < n) {
sz <<= 1;
height++;
}
data.assign(sz * 2, e());
fail.assign(sz * 2, false);
lazy.assign(sz * 2, id());
}
public:
/**
* @brief コンストラクタ
*
* @param n 要素数
* @param a 作用素付きモノイド
*/
explicit SegTreeBeats(long long n = 0, A a = A()) : a(std::move(a)), n(n) {
construct_data();
}
/**
* @brief コンストラクタ
*
* @param v 初期の要素
* @param a 作用素付きモノイド
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit SegTreeBeats(R&& v, A a = A()) : SegTreeBeats(internal_traits::range_size(v), std::move(a)) {
long long k = sz;
for (auto&& x : v) data[k++] = S(std::forward<decltype(x)>(x));
for (long long i = sz - 1; i > 0; i--) update(i);
}
/**
* @brief 要素数を返す
*/
long long size() const { return n; }
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S get(long long k) {
assert(0 <= k && k < n);
k += sz;
for (int h = height; h > 0; h--) {
push(k >> h, h);
}
return data[k];
}
/**
* @brief 指定された要素への参照を返す
*
* @param k
* @return SegTreeReference 要素への参照 代入されるとset()が呼ばれる
*/
SegTreeBeatsReference operator[](long long k) { return SegTreeBeatsReference(*this, k); }
/**
* @brief 内容を出力する
*
* @tparam CharT 出力ストリームの文字型
* @tparam Traits 出力ストリームの文字型特性
* @param os 出力ストリーム
* @param rhs セグメント木
* @return std::basic_ostream<CharT, Traits>& 出力ストリーム
*/
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, SegTreeBeats& rhs) {
for (long long i = 0; i < rhs.n; i++) {
if (i != 0) os << CharT(' ');
os << rhs[i];
}
return os;
}
/**
* @brief 指定された要素の値をxに更新する
*
* @param k インデックス
* @param x 新しい値
*/
void set(long long k, const S& x) {
assert(0 <= k && k < n);
k += sz;
for (int h = height; h > 0; h--) {
push(k >> h, h);
}
data[k] = x;
while (k >>= 1) update(k);
}
/**
* @brief [l, r)の区間の総積を返す
*
* @param l 半開区間の開始
* @param r 半開区間の終端
* @return S 総積
*/
S prod(long long l, long long r) {
assert(0 <= l && l <= r && r <= n);
l += sz;
r += sz;
for (int h = height; h > 0; h--) {
if (((l >> h) << h) != l) push(l >> h, h);
if (((r >> h) << h) != r) push(r >> h, h);
}
S left_prod = e(), right_prod = e();
while (l < r) {
if (l & 1) left_prod = op(left_prod, data[l++]);
if (r & 1) right_prod = op(data[--r], right_prod);
l >>= 1;
r >>= 1;
}
return op(left_prod, right_prod);
}
/**
* @brief すべての要素の総積を返す
*
* @return S 総積
*/
S all_prod() const { return data[1]; }
/**
* @brief 指定された要素の値にxを作用させる
*
* @param k インデックス
* @param x 作用素
*/
void apply(long long k, const F& f) {
assert(0 <= k && k < n);
k += sz;
for (int h = height; h > 0; h--) {
push(k >> h, h);
}
data[k] = mapping(f, data[k], k - sz, k - sz + 1).second;
while (k >>= 1) update(k);
}
/**
* @brief [l, r)の区間の値にxを作用させる
*
* @param l 半開区間の開始
* @param r 半開区間の終端
* @param f 作用素
*/
void apply(long long l, long long r, const F& f) {
assert(0 <= l && l <= r && r <= n);
if (l == r) return;
l += sz;
r += sz;
for (int h = height; h > 0; h--) {
if (((l >> h) << h) != l) push(l >> h, h);
if (((r >> h) << h) != r) push(r >> h, h);
}
{
long long l2 = l, r2 = r;
int h = 0;
while (l < r) {
if (l & 1) apply_node(l++, h, f);
if (r & 1) apply_node(--r, h, f);
l >>= 1;
r >>= 1;
h++;
}
l = l2;
r = r2;
}
for (int h = 1; h <= height; h++) {
if (((l >> h) << h) != l) update(l >> h);
if (((r >> h) << h) != r) update((r - 1) >> h);
}
}
/**
* @brief (r = l or g(prod([l, r))) = true) and (r = n or g(prod([l, r+1))) = false)となるrを返す
* gが単調なら、g(prod([l, r))) = trueとなる最大のr
*
* @tparam G
* @param l 半開区間の開始
* @param g 判定関数 g(e) = true
* @return long long
*/
template <typename G>
long long max_right(long long l, G g) {
assert(g(e()));
assert(0 <= l && l <= n);
if (l == n) return n;
l += sz;
for (int h = height; h > 0; h--) {
push(l >> h, h);
}
int h = 0;
while (l % 2 == 0) {
l >>= 1;
h++;
}
S sum = e();
while (g(op(sum, data[l]))) {
sum = op(sum, data[l]);
l++;
while (l % 2 == 0) {
l >>= 1;
h++;
}
if (l == 1) return n;
}
while (l < sz) {
push(l, h);
if (!g(op(sum, data[l * 2]))) {
l = l * 2;
} else {
sum = op(sum, data[l * 2]);
l = l * 2 + 1;
}
h--;
}
return l - sz;
}
/**
* @brief (l = 0 or g(prod([l, r))) = true) and (l = r or g(prod([l-1, r))) = false)となるlを返す
* gが単調なら、g(prod([l, r))) = trueとなる最小のl
*
* @tparam G
* @param r 半開区間の終端
* @param g 判定関数 g(e) = true
* @return long long
*/
template <typename G>
long long min_left(long long r, G g) {
assert(g(e()));
assert(0 <= r && r <= n);
if (r == 0) return 0;
r += sz;
for (int h = height; h > 0; h--) {
push((r - 1) >> h, h);
}
int h = 0;
S sum = e();
do {
r--;
while (r > 1 && r % 2 == 1) {
r >>= 1;
h++;
}
if (!g(op(data[r], sum))) {
while (r < sz) {
push(r, h);
r = r * 2 + 1;
h--;
if (g(op(data[r], sum))) {
sum = op(data[r], sum);
r--;
}
}
return r + 1 - sz;
}
sum = op(data[r], sum);
} while ((r & -r) != r);
return 0;
}
};
template <typename A>
SegTreeBeats(long long, A) -> SegTreeBeats<A>;
template <class R, typename A>
SegTreeBeats(R&&, A) -> SegTreeBeats<A>;
template <typename A>
SegTreeBeats(std::initializer_list<typename A::S>, A) -> SegTreeBeats<A>;
/**
* @brief 区間 chmin、区間和・最大値
*
* @tparam S 型
*/
template <typename S>
using RChminSumQ = SegTreeBeats<beats_acted_monoid::ChminSum<S>>;
/**
* @brief 区間 chmax、区間和・最小値
*
* @tparam S 型
*/
template <typename S>
using RChmaxSumQ = SegTreeBeats<beats_acted_monoid::ChmaxSum<S>>;
/**
* @brief 区間 chmin・chmax・加算・代入、区間和・最大値・最小値
*
* @tparam S 型
*/
template <typename S>
using RChminChmaxAddSumQ = SegTreeBeats<beats_acted_monoid::ChminChmaxAddSum<S>>;
#line 2 "src/data_structures/segtree.hpp"
/**
* @file segtree.hpp
* @brief セグメント木
*/
#line 15 "src/data_structures/segtree.hpp"
#line 18 "src/data_structures/segtree.hpp"
/**
* @brief セグメント木
*
* 例:
* SegTree<monoid::Max<int>> seg(n);
* SegTree seg(v, Monoid([](int a, int b) { return a + b; }, 0));
*
* @tparam M モノイド (algebra/monoid.hpp)
*/
template <typename M>
class SegTree {
public:
using S = typename M::S;
private:
M m;
S op(const S& a, const S& b) const { return m.op(a, b); }
S e() const { return m.e(); }
long long n, sz;
int height;
std::vector<S> data;
void update(long long k) { data[k] = op(data[2 * k], data[2 * k + 1]); }
class SegTreeReference {
SegTree& segtree;
long long k;
public:
SegTreeReference(SegTree& segtree, long long k) : segtree(segtree), k(k) {}
SegTreeReference& operator=(const S& x) {
segtree.set(k, x);
return *this;
}
operator S() const { return segtree.get(k); }
};
void construct_data() {
sz = 1;
height = 0;
while (sz < n) {
sz <<= 1;
height++;
}
data.assign(sz * 2, e());
}
public:
/**
* @brief コンストラクタ
*
* @param n 要素数
* @param m モノイド
*/
explicit SegTree(long long n = 0, M m = M()) : m(std::move(m)), n(n) {
construct_data();
}
/**
* @brief コンストラクタ
*
* @param v 初期の要素
* @param m モノイド
*/
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit SegTree(R&& v, M m = M()) : SegTree(static_cast<long long>(internal_traits::range_size(v)), std::move(m)) {
long long k = sz;
for (auto&& x : v) data[k++] = S(std::forward<decltype(x)>(x));
for (long long i = sz - 1; i > 0; i--) update(i);
}
/**
* @brief 要素数を返す
*/
long long size() const { return n; }
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S get(long long k) const {
assert(0 <= k && k < n);
return data[sz + k];
}
/**
* @brief 指定された要素の値を返す
*
* @param k インデックス
* @return S 値
*/
S operator[](long long k) const { return get(k); }
/**
* @brief 指定された要素への参照を返す
*
* @param k
* @return SegTreeReference 要素への参照 代入されるとset()が呼ばれる
*/
SegTreeReference operator[](long long k) { return SegTreeReference(*this, k); }
/**
* @brief 内容を出力する
*
* @tparam CharT 出力ストリームの文字型
* @tparam Traits 出力ストリームの文字型特性
* @param os 出力ストリーム
* @param rhs セグメント木
* @return std::basic_ostream<CharT, Traits>& 出力ストリーム
*/
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const SegTree& rhs) {
for (long long i = 0; i < rhs.n; i++) {
if (i != 0) os << CharT(' ');
os << rhs[i];
}
return os;
}
/**
* @brief 指定された要素の値をxに更新する
*
* @param k インデックス
* @param x 新しい値
*/
void set(long long k, const S& x) {
assert(0 <= k && k < n);
k += sz;
data[k] = x;
for (int i = 1; i <= height; i++) update(k >> i);
}
/**
* @brief 指定された要素の値にxを作用させる
*
* @param k インデックス
* @param x 作用素
*/
void apply(long long k, const S& x) { set(k, op(get(k), x)); }
/**
* @brief [l, r)の区間の総積を返す
*
* @param l 半開区間の開始
* @param r 半開区間の終端 0<=l<=r<=n
* @return S 総積
*/
S prod(long long l, long long r) const {
assert(0 <= l && l <= r && r <= n);
S left_prod = e(), right_prod = e();
l += sz;
r += sz;
while (l < r) {
if (l & 1) left_prod = op(left_prod, data[l++]);
if (r & 1) right_prod = op(data[--r], right_prod);
l >>= 1;
r >>= 1;
}
return op(left_prod, right_prod);
}
/**
* @brief すべての要素の総積を返す
*
* @return S 総積
*/
S all_prod() const { return data[1]; }
/**
* @brief (r = l or f(prod([l, r))) = true) and (r = n or f(prod([l, r+1))) = false)となるrを返す
* fが単調なら、f(prod([l, r))) = trueとなる最大のr
*
* @tparam F
* @param l 半開区間の開始 0<=l<=n
* @param f 判定関数 f(e) = true
* @return long long
*/
template <typename F>
long long max_right(long long l, F f) const {
assert(f(e()));
assert(0 <= l && l <= n);
if (l == n) return n;
l += sz;
while (l % 2 == 0) l >>= 1;
S sum = e();
while (f(op(sum, data[l]))) {
sum = op(sum, data[l]);
l++;
while (l % 2 == 0) l >>= 1;
if (l == 1) return n;
}
while (l < sz) {
if (!f(op(sum, data[l * 2])))
l *= 2;
else {
sum = op(sum, data[l * 2]);
l = l * 2 + 1;
}
}
return l - sz;
}
/**
* @brief (l = 0 or f(prod([l, r))) = true) and (l = r or f(prod([l-1, r))) = false)となるlを返す
* fが単調なら、f(prod([l, r))) = trueとなる最小のl
*
* @tparam F
* @param r 半開区間の終端 0<=r<=n
* @param f 判定関数 f(e) = true
* @return long long
*/
template <typename F>
long long min_left(long long r, F f) const {
assert(f(e()));
assert(0 <= r && r <= n);
if (r == 0) return 0;
r += sz;
S sum = e();
do {
r--;
while (r > 1 && r % 2 == 1) r >>= 1;
if (!f(op(data[r], sum))) {
while (r < sz) {
r = r * 2 + 1;
if (f(op(data[r], sum))) {
sum = op(data[r], sum);
r--;
}
}
return r + 1 - sz;
}
sum = op(data[r], sum);
} while ((r & -r) != r);
return 0;
}
};
template <typename M>
SegTree(long long, M) -> SegTree<M>;
template <class R, typename M>
SegTree(R&&, M) -> SegTree<M>;
template <typename M>
SegTree(std::initializer_list<typename M::S>, M) -> SegTree<M>;
/**
* @brief RangeMaxQuery
*
* @tparam S 型
*/
template <typename S>
using RMaxQ = SegTree<monoid::Max<S>>;
/**
* @brief RangeMinQuery
*
* @tparam S 型
*/
template <typename S>
using RMinQ = SegTree<monoid::Min<S>>;
/**
* @brief RangeSumQuery
*
* @tparam S 型
*/
template <typename S>
using RSumQ = SegTree<monoid::Sum<S>>;
/**
* @brief RangeProdQuery
*
* @tparam S 型
*/
template <typename S>
using RProdQ = SegTree<monoid::Prod<S>>;
/**
* @brief RangeXorQuery
*
* @tparam S 型
*/
template <typename S>
using RXorQ = SegTree<monoid::Xor<S>>;
/**
* @brief RangeGcdQuery
*
* @tparam S 型
*/
template <typename S>
using RGcdQ = SegTree<monoid::Gcd<S>>;
#line 2 "src/data_structures/sortable-segtree.hpp"
/**
* @file sortable-segtree.hpp
* @brief 区間ソートのできるセグメント木
*/
#line 13 "src/data_structures/sortable-segtree.hpp"
#line 2 "src/data_structures/fast-set.hpp"
/**
* @file fast-set.hpp
* @brief 64 分木による整数の集合 (FastSet)
*/
#line 11 "src/data_structures/fast-set.hpp"
/**
* @brief [0, n) の整数の集合を 64 分木で持つ
*
* 各段は 64 bit の配列で、上の段の bit は下の段の 64 bit が 0 でないかを表す
* 挿入・削除・x 以上の最小・x 以下の最大を O(log_64 n) で行う (n = 10^9 でも 5 段程度)
* 例:
* FastSet s(n);
* s.insert(3); s.insert(10);
* s.next(4); // 10
* s.prev(4); // 3
*/
class FastSet {
long long n, cnt = 0;
std::vector<std::vector<std::uint64_t>> seg; // seg[0] が要素の bit、seg[h + 1] は seg[h] の各 64 bit が 0 でないか
void build_levels() {
// 1 つの 64 bit に収まるまで段を重ねる
do {
long long m = seg.empty() ? n : static_cast<long long>(seg.back().size());
seg.emplace_back((m + 63) / 64, 0);
} while (seg.back().size() > 1);
}
public:
/**
* @brief [0, n) の空の集合
*/
explicit FastSet(long long n = 0) : n(n) {
assert(n >= 0);
build_levels();
}
/**
* @brief v[i] が true の i からなる集合 O(n)
*/
explicit FastSet(const std::vector<bool>& v) : FastSet(static_cast<long long>(v.size())) {
for (long long i = 0; i < n; i++) {
if (v[i]) seg[0][i >> 6] |= std::uint64_t(1) << (i & 63), cnt++;
}
for (int h = 0; h + 1 < static_cast<int>(seg.size()); h++) {
for (long long i = 0; i < static_cast<long long>(seg[h].size()); i++) {
if (seg[h][i]) seg[h + 1][i >> 6] |= std::uint64_t(1) << (i & 63);
}
}
}
/**
* @brief 扱える整数の範囲 [0, n) の n
*/
long long limit() const { return n; }
/**
* @brief 要素数
*/
long long size() const { return cnt; }
/**
* @brief 空か
*/
bool empty() const { return cnt == 0; }
/**
* @brief x が含まれるか O(1)
*/
bool contains(long long x) const {
assert(0 <= x && x < n);
return seg[0][x >> 6] >> (x & 63) & 1;
}
/**
* @brief x の個数 (0 か 1) O(1)
*/
long long count(long long x) const { return contains(x); }
/**
* @brief x を挿入する。新しく入ったら true O(log_64 n)
*/
bool insert(long long x) {
assert(0 <= x && x < n);
if (contains(x)) return false;
cnt++;
for (auto& level : seg) {
level[x >> 6] |= std::uint64_t(1) << (x & 63);
x >>= 6;
}
return true;
}
/**
* @brief x を削除する。入っていたら true O(log_64 n)
*/
bool erase(long long x) {
assert(0 <= x && x < n);
if (!contains(x)) return false;
cnt--;
for (auto& level : seg) {
level[x >> 6] &= ~(std::uint64_t(1) << (x & 63));
// 同じ 64 bit に他の要素が残っていれば、上の段は変わらない
if (level[x >> 6]) break;
x >>= 6;
}
return true;
}
/**
* @brief x 以上の最小の要素 (なければ -1) O(log_64 n)
*/
long long next(long long x) const {
if (x < 0) x = 0;
if (x >= n) return -1;
for (int h = 0; h < static_cast<int>(seg.size()); h++) {
if ((x >> 6) == static_cast<long long>(seg[h].size())) break;
std::uint64_t d = seg[h][x >> 6] >> (x & 63);
if (!d) {
x = (x >> 6) + 1;
continue;
}
// この段で見つかったので、下の段では最も小さい bit をたどる
x += __builtin_ctzll(d);
for (int g = h - 1; g >= 0; g--) {
x <<= 6;
x += __builtin_ctzll(seg[g][x >> 6]);
}
return x;
}
return -1;
}
/**
* @brief x 以下の最大の要素 (なければ -1) O(log_64 n)
*/
long long prev(long long x) const {
if (x >= n) x = n - 1;
if (x < 0) return -1;
for (int h = 0; h < static_cast<int>(seg.size()); h++) {
if (x == -1) break;
std::uint64_t d = seg[h][x >> 6] << (63 - (x & 63));
if (!d) {
x = (x >> 6) - 1;
continue;
}
// この段で見つかったので、下の段では最も大きい bit をたどる
x -= __builtin_clzll(d);
for (int g = h - 1; g >= 0; g--) {
x <<= 6;
x += 63 - __builtin_clzll(seg[g][x >> 6]);
}
return x;
}
return -1;
}
/**
* @brief 最小の要素 (空なら -1) O(log_64 n)
*/
long long min() const { return next(0); }
/**
* @brief 最大の要素 (空なら -1) O(log_64 n)
*/
long long max() const { return prev(n - 1); }
/**
* @brief 要素を昇順に並べたもの O(size() log_64 n)
*/
std::vector<long long> to_vector() const {
std::vector<long long> res;
res.reserve(cnt);
for (long long x = next(0); x != -1; x = next(x + 1)) res.push_back(x);
return res;
}
/**
* @brief すべて削除する O(n / 64)
*/
void clear() {
for (auto& level : seg) level.assign(level.size(), 0);
cnt = 0;
}
};
#line 17 "src/data_structures/sortable-segtree.hpp"
/**
* @brief 各位置にキーと値を持つ列で、1 点の変更・区間の積・区間をキーで並べ替える操作を行う
*
* 並べ替えた区間ごとに、その要素をキーの二分トライ (動的セグメント木) で持ち、昇順と降順の積を保つ。
* 区間の先頭の位置に「区間の向きに合わせた積」を置いたセグメント木で区間の積を求める。
* 並べ替えはトライの併合、区間の境目はトライを個数で分けることで作る
* 計算量はならし O((N + Q) log K) (K はキーの上限)。メモリは O((N + Q) log K)
* 例:
* SortableSegTree<monoid::Sum<long long>> st(keys, values, 1LL << 30);
* st.sort(l, r); // [l, r) をキーの昇順に並べ替える
* st.sort(l, r, true); // 降順
* st.prod(l, r);
*
* @tparam M モノイド (積の順番は列の順番)
*/
template <typename M>
class SortableSegTree {
using S = typename M::S;
struct Node {
int child[2] = {0, 0};
int cnt = 0;
S asc, desc; // キーの昇順・降順に並べたときの積
};
M m;
long long n;
int bits;
std::vector<Node> nodes; // nodes[0] は空のトライ
std::vector<int> root; // root[s]: s から始まる区間のトライ
std::vector<bool> rev; // rev[s]: s から始まる区間が降順か
FastSet starts; // 区間の先頭
SegTree<M> seg;
int new_node() {
nodes.push_back(Node{{0, 0}, 0, m.e(), m.e()});
return static_cast<int>(nodes.size()) - 1;
}
void pull(int t) {
const Node &a = nodes[nodes[t].child[0]], &b = nodes[nodes[t].child[1]];
nodes[t].cnt = a.cnt + b.cnt;
nodes[t].asc = m.op(a.asc, b.asc);
nodes[t].desc = m.op(b.desc, a.desc);
}
// キー k、値 x だけを持つトライ
int make(long long k, const S& x) {
assert(0 <= k && k < (1LL << bits));
std::vector<int> path = {new_node()};
for (int d = bits - 1; d >= 0; d--) {
const int c = new_node();
nodes[path.back()].child[k >> d & 1] = c;
path.push_back(c);
}
nodes[path.back()].cnt = 1, nodes[path.back()].asc = nodes[path.back()].desc = x;
for (int i = static_cast<int>(path.size()) - 2; i >= 0; i--) pull(path[i]);
return path[0];
}
// 2 つのトライを併合する (キーは重ならないこと)
int merge(int a, int b, int d) {
if (a == 0) return b;
if (b == 0) return a;
assert(d >= 0 && "SortableSegTree: キーが重なっている");
for (int c = 0; c < 2; c++) {
int x = merge(nodes[a].child[c], nodes[b].child[c], d - 1);
nodes[a].child[c] = x;
}
pull(a);
return a;
}
// キーの小さい方から k 個と残りに分ける
std::pair<int, int> split(int t, int k, int d) {
if (t == 0 || k == 0) return {0, t};
if (k >= nodes[t].cnt) return {t, 0};
// ここに来るなら cnt >= 2 なので葉ではない
int s = new_node();
const int lc = nodes[t].child[0], left_cnt = nodes[lc].cnt;
if (k <= left_cnt) {
auto [a, b] = split(lc, k, d - 1);
nodes[t].child[0] = a;
nodes[s].child[0] = b, nodes[s].child[1] = nodes[t].child[1];
nodes[t].child[1] = 0;
} else {
auto [a, b] = split(nodes[t].child[1], k - left_cnt, d - 1);
nodes[t].child[1] = a;
nodes[s].child[1] = b;
}
pull(t), pull(s);
return {t, s};
}
// 区間の積を向きに合わせて返す
S value(int s) const { return rev[s] ? nodes[root[s]].desc : nodes[root[s]].asc; }
// x が区間の先頭になるように分ける
void cut(long long x) {
if (x >= n || starts.contains(x)) return;
const long long s = starts.prev(x);
const int len = nodes[root[s]].cnt, k = x - s;
int a, b;
if (!rev[s]) {
std::tie(a, b) = split(root[s], k, bits - 1);
} else {
// 降順なので、先頭の k 個はキーの大きい方の k 個
std::tie(b, a) = split(root[s], len - k, bits - 1);
}
root[s] = a, root[x] = b, rev[x] = rev[s];
starts.insert(x);
seg.set(s, value(s)), seg.set(x, value(x));
}
public:
/**
* @brief キーと値の列から作る
* @param keys キー (0 <= キー < key_limit、すべて異なること)
* @param key_limit キーの上限 (1 点の変更で使うキーもこれ未満であること)
*/
#if __cplusplus >= 202002L
template <class K = std::initializer_list<long long>, class R = std::initializer_list<S>>
requires(internal_traits::sized_constructible_range<K, long long> && internal_traits::sized_constructible_range<R, S>)
#else
template <class K = std::initializer_list<long long>, class R = std::initializer_list<S>,
ENABLE_IF_T(internal_traits::is_sized_constructible_range<K, long long>::value&& internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
SortableSegTree(K&& keys, R&& values, long long key_limit, M m = M())
: m(m), n(internal_traits::range_size(keys)), bits(1), root(n), rev(n, false), starts(n), seg(values, m) {
assert(n == static_cast<long long>(internal_traits::range_size(values)));
while ((1LL << bits) < key_limit) bits++;
nodes.reserve(n * (bits + 2) + 1);
nodes.push_back(Node{{0, 0}, 0, this->m.e(), this->m.e()});
long long i = 0;
for (auto&& key : keys) {
root[i] = make(static_cast<long long>(std::forward<decltype(key)>(key)), seg.get(i));
starts.insert(i++);
}
}
/**
* @brief 要素数
*/
long long size() const { return n; }
/**
* @brief 位置 i のキーと値を変える ならし O(log K)
*/
void set(long long i, long long k, const S& x) {
assert(0 <= i && i < n);
cut(i), cut(i + 1);
root[i] = make(k, x), rev[i] = false;
seg.set(i, x);
}
/**
* @brief a[l] a[l+1] ... a[r-1] の積 ならし O(log K + log N)
*/
S prod(long long l, long long r) {
assert(0 <= l && l <= r && r <= n);
if (l == r) return m.e();
cut(l), cut(r);
return seg.prod(l, r);
}
/**
* @brief [l, r) をキーの昇順 (reverse なら降順) に並べ替える ならし O(log K + 区間の個数)
*/
void sort(long long l, long long r, bool reverse = false) {
assert(0 <= l && l <= r && r <= n);
if (l == r) return;
cut(l), cut(r);
int t = 0;
for (long long s = l; s != -1 && s < r; s = starts.next(s + 1)) {
t = merge(t, root[s], bits - 1);
if (s != l) starts.erase(s), seg.set(s, m.e()), root[s] = 0;
}
root[l] = t, rev[l] = reverse;
seg.set(l, value(l));
}
};
template <class K, class R, typename M>
SortableSegTree(K&&, R&&, long long, M) -> SortableSegTree<M>;
template <typename M>
SortableSegTree(std::initializer_list<long long>, std::initializer_list<typename M::S>, long long, M) -> SortableSegTree<M>;
#line 2 "src/data_structures/sparse-table.hpp"
/**
* @file sparse-table.hpp
* @brief Sparse Table
*/
#line 13 "src/data_structures/sparse-table.hpp"
#line 16 "src/data_structures/sparse-table.hpp"
/**
* @brief Sparse Table
*
* 静的な列の区間積を、前計算 O(n log n)、クエリ O(1) で求める
* 例:
* SparseTable<monoid::Min<int>> st(v);
* st.prod(l, r); // min(v[l], ..., v[r-1])
*
* @tparam M 冪等なモノイド (op(x, x) = x となるもの。monoid::Min、Max、Gcd、And、Or など)
*/
template <typename M>
class SparseTable {
public:
using S = typename M::S;
private:
M m;
long long n;
// table[k][i] は v[i] から v[i + 2^k - 1] までの積
std::vector<std::vector<S>> table;
std::vector<int> lg; // lg[x] = floor(log2(x))
S op(const S& a, const S& b) const { return m.op(a, b); }
S e() const { return m.e(); }
public:
#if __cplusplus >= 202002L
template <class R = std::initializer_list<S>>
requires internal_traits::sized_constructible_range<R, S>
#else
template <class R = std::initializer_list<S>, ENABLE_IF_T(internal_traits::is_sized_constructible_range<R, S>::value)>
#endif
explicit SparseTable(R&& v = {}, M m = M()) : m(std::move(m)), n(internal_traits::range_size(v)), lg(n + 1, 0) {
table.emplace_back();
table[0].reserve(n);
for (auto&& x : v) table[0].emplace_back(std::forward<decltype(x)>(x));
for (long long x = 2; x <= n; x++) lg[x] = lg[x / 2] + 1;
for (int k = 1; (1LL << k) <= n; k++) {
const auto& prev = table[k - 1];
std::vector<S> cur(n - (1LL << k) + 1);
for (long long i = 0; i + (1LL << k) <= n; i++) cur[i] = op(prev[i], prev[i + (1LL << (k - 1))]);
table.push_back(std::move(cur));
}
}
long long size() const { return n; }
/**
* @brief v[k]
*/
S get(long long k) const {
assert(0 <= k && k < n);
return table[0][k];
}
/**
* @brief v[l] から v[r-1] までの積 O(1)。l = r なら単位元
*/
S prod(long long l, long long r) const {
assert(0 <= l && l <= r && r <= n);
if (l == r) return e();
int k = lg[r - l];
return op(table[k][l], table[k][r - (1LL << k)]);
}
S all_prod() const { return prod(0, n); }
};
template <class R, typename M>
SparseTable(R&&, M) -> SparseTable<M>;
template <typename M>
SparseTable(std::initializer_list<typename M::S>, M) -> SparseTable<M>;
#line 37 "test/unittest/algebra/monoid.test.cpp"
bool ok = true;
void check(bool cond, const char* what) {
if (!cond && ok) std::cerr << "failed: " << what << std::endl;
if (!cond) ok = false;
}
// SegTree<M> を、配列と演算 op で愚直に計算した結果とランダムな操作列で比べる
// size・const な operator[]・all_prod・os << seg も確かめる
template <typename M, typename Op, typename Gen>
void test_segtree(Op op, typename M::S e, Gen gen, std::mt19937_64& rng, const char* name) {
using S = typename M::S;
for (int rep = 0; rep < 200 && ok; rep++) {
int n = rng() % 20 + 1;
std::vector<S> a(n);
for (auto& x : a) x = gen();
SegTree<M> seg(a);
check(seg.size() == n, name);
for (int q = 0; q < 50 && ok; q++) {
int t = rng() % 3;
if (t == 0) {
int k = rng() % n;
S x = gen();
seg.set(k, x);
a[k] = x;
} else if (t == 1) {
int k = rng() % n;
S x = gen();
seg.apply(k, x);
a[k] = op(a[k], x);
} else {
int l = rng() % (n + 1), r = rng() % (n + 1);
if (l > r) std::swap(l, r);
S expect = e;
for (int i = l; i < r; i++) expect = op(expect, a[i]);
check(seg.prod(l, r) == expect, name);
}
}
S all = e;
for (int i = 0; i < n; i++) all = op(all, a[i]);
check(seg.all_prod() == all, name);
const SegTree<M>& cseg = seg;
std::ostringstream os, expect;
for (int i = 0; i < n; i++) {
check(cseg[i] == a[i], name);
if (i != 0) expect << ' ';
expect << a[i];
}
os << cseg;
check(os.str() == expect.str(), name);
}
}
struct ExplicitSum {
struct S {
long long value;
S() : value(0) {}
explicit S(long long x) : value(x) {}
};
static S op(const S& a, const S& b) { return S(a.value + b.value); }
static S e() { return S(0); }
};
struct ExplicitAddSum : ExplicitSum {
using F = long long;
static S mapping(F f, const S& x, long long len) { return S(x.value + f * len); }
static F composition(F f, F g) { return f + g; }
static F id() { return 0; }
static F inv(F f) { return -f; }
};
struct ExplicitGroup : ExplicitSum {
static S inv(const S& x) { return S(-x.value); }
};
struct ExplicitMin : ExplicitSum {
static S op(const S& a, const S& b) { return S(std::min(a.value, b.value)); }
static S e() { return S(std::numeric_limits<long long>::max()); }
};
struct ExplicitBeats : ExplicitAddSum {
static std::pair<bool, S> mapping(F f, const S& x, long long len) { return {false, ExplicitAddSum::mapping(f, x, len)}; }
};
// begin は一度だけ。イテレータの後置 ++ は値を返さず、終端の型も異なる。
struct SizedInputRange {
int values[3] = {2, -5, 4};
int pos = 0;
bool begun = false;
struct Sentinel {};
struct Iterator {
using value_type = int;
using difference_type = long long;
using iterator_category = std::input_iterator_tag;
SizedInputRange* range;
int operator*() const { return range->values[range->pos]; }
Iterator& operator++() {
++range->pos;
return *this;
}
void operator++(int) { ++*this; }
friend bool operator==(Iterator it, Sentinel) { return it.range->pos == 3; }
friend bool operator!=(Iterator it, Sentinel s) { return !(it == s); }
friend bool operator==(Sentinel s, Iterator it) { return it == s; }
friend bool operator!=(Sentinel s, Iterator it) { return !(it == s); }
};
Iterator begin() {
check(!begun, "sized input range is traversed once");
begun = true;
return {this};
}
Sentinel end() const { return {}; }
long long size() const { return 3; }
};
template <template <typename> class Tree, typename M>
void test_converting_tree(M m) {
auto verify_range = [&](auto&& r) {
Tree tree(std::forward<decltype(r)>(r), m);
check(tree.size() == 3 && tree.get(0).value == 2 && tree.get(1).value == -5 && tree.get(2).value == 4,
"tree family sized range / CTAD");
};
int raw[] = {2, -5, 4};
const std::array<int, 3> arr = {2, -5, 4};
verify_range(raw);
verify_range(arr);
verify_range(std::list<int>{2, -5, 4});
verify_range(std::deque<int>{2, -5, 4});
verify_range(SizedInputRange{});
Tree<M> empty_array(std::array<int, 0>{});
check(empty_array.size() == 0, "tree family empty array");
static_assert(!std::is_constructible_v<Tree<M>, std::forward_list<int>&>);
static_assert(!std::is_constructible_v<Tree<M>, std::array<std::string, 3>&>);
#if __cplusplus >= 202002L
verify_range(std::views::iota(0, 3) | std::views::transform([&](int i) { return raw[i]; }));
#endif
static_assert(std::is_constructible_v<Tree<M>, const std::vector<int>&, M>);
static_assert(!std::is_constructible_v<Tree<M>, const std::vector<std::string>&, M>);
Tree seg(std::vector<int>{2, -5, 4}, m);
check(seg.size() == 3 && seg.get(0).value == 2 && seg.get(1).value == -5 && seg.get(2).value == 4,
"segtree family explicit conversion / CTAD");
Tree<M> empty(std::vector<int>{});
check(empty.size() == 0, "segtree family conversion empty");
Tree<M> same(std::vector<typename M::S>{typename M::S(7)});
check(same.get(0).value == 7, "segtree family vector<S>");
Tree<M> list({typename M::S(8), typename M::S(9)});
check(list.get(1).value == 9, "segtree family initializer list");
}
template <class R>
void test_segtree_range(R&& r) {
SegTree seg(std::forward<R>(r), ExplicitSum{});
check(seg.size() == 3 && seg.prod(0, 3).value == 1 && seg.prod(1, 3).value == -1, "SegTree sized range / CTAD");
seg.set(1, ExplicitSum::S(3));
check(seg.all_prod().value == 9, "SegTree sized range update");
}
int main() {
{
using M = monoid::MinMax<>;
constexpr M::S single(7);
static_assert(single.min == 7 && single.max == 7);
static_assert(M::e() == M::S());
std::vector<long long> values = {3, -5, 8, 8, 0};
SegTree<M> seg(values);
for (long long l = 0; l <= 5; ++l) {
for (long long r = l; r <= 5; ++r) {
long long mn = std::numeric_limits<long long>::max(), mx = std::numeric_limits<long long>::lowest();
for (long long i = l; i < r; ++i) {
mn = std::min(mn, values[i]);
mx = std::max(mx, values[i]);
}
auto [actual_min, actual_max] = seg.prod(l, r);
check(actual_min == mn && actual_max == mx, "MinMax members and structured binding");
check(seg.prod(l, r) == M::S(mn, mx), "MinMax equality");
check(M::op(M::e(), seg.prod(l, r)) == seg.prod(l, r) && M::op(seg.prod(l, r), M::e()) == seg.prod(l, r), "MinMax identity");
}
}
check(!(M::S(1) != M::S(1)) && M::S(1) != M::S(2), "MinMax inequality");
using A = acted_monoid::ClampMinMax<long long>;
using B = acted_monoid::ClampAddMinMax<long long>;
check(A::mapping({0, 10}, M::e()) == M::e(), "ClampMinMax empty");
check(B::mapping({{}, {}, 3}, M::e()) == M::e(), "ClampAddMinMax empty");
}
{
int a[] = {2, -5, 4};
const std::array<int, 3> b = {2, -5, 4};
test_segtree_range(a);
test_segtree_range(b);
test_segtree_range(std::list<int>{2, -5, 4});
test_segtree_range(std::deque<int>{2, -5, 4});
SegTree<ExplicitSum> empty(std::array<int, 0>{});
check(empty.size() == 0 && empty.all_prod().value == 0, "SegTree empty range");
SegTree braces({ExplicitSum::S(2), ExplicitSum::S(-5), ExplicitSum::S(4)}, ExplicitSum{});
check(braces.all_prod().value == 1, "SegTree initializer list / CTAD");
SegTree<ExplicitSum> original(a);
auto copied = original;
auto moved = std::move(copied);
check(moved.all_prod().value == 1 && original.all_prod().value == 1, "SegTree copy / move");
SegTree sized(3LL, ExplicitSum{});
check(sized.size() == 3 && sized.all_prod().value == 0, "SegTree size / CTAD");
static_assert(!std::is_constructible_v<SegTree<ExplicitSum>, std::forward_list<int>&>);
static_assert(!std::is_constructible_v<SegTree<ExplicitSum>, std::array<std::string, 3>&>);
#if __cplusplus >= 202002L
test_segtree_range(std::views::all(a));
test_segtree_range(std::views::iota(0, 3) | std::views::transform([&](int i) { return a[i]; }));
SegTree view(a | std::views::take(2), ExplicitSum{});
check(view.size() == 2 && view.all_prod().value == -3, "SegTree partial view");
#endif
}
test_converting_tree<SegTree>(ExplicitSum{});
test_converting_tree<RBST>(ExplicitSum{});
test_converting_tree<RBST>(ExplicitAddSum{});
test_converting_tree<FenwickTree>(ExplicitGroup{});
test_converting_tree<SparseTable>(ExplicitMin{});
test_converting_tree<LinkCutTree>(ExplicitSum{});
test_converting_tree<SubtreeLinkCutTree>(ExplicitGroup{});
{
auto verify = [](auto&& r) {
MonoidUnionFind uf(std::forward<decltype(r)>(r), ExplicitSum{});
uf.merge(0, 1);
check(uf.prod(0).value == -3 && uf.prod(2).value == 4, "MonoidUnionFind sized range / CTAD");
};
int raw[] = {2, -5, 4};
verify(raw);
verify(std::list<int>{2, -5, 4});
verify(SizedInputRange{});
std::vector<ExplicitSum::S> owned{ExplicitSum::S(7)};
const auto* ptr = owned.data();
MonoidUnionFind moved(std::move(owned), ExplicitSum{});
check(&moved.prod(0) == ptr, "MonoidUnionFind moves vector storage");
Imos from_range(SizedInputRange{}, ExplicitAddSum{});
from_range.apply(0, 2, 3);
check(from_range.get(0).value == 5 && from_range.get(1).value == -2 && from_range.get(2).value == 4,
"Imos sized input range / CTAD");
Imos from_list(std::list<int>{2, -5, 4}, ExplicitAddSum{});
check(from_list.get(1).value == -5, "Imos list");
Imos<ExplicitAddSum> empty_range(std::array<int, 0>{});
static_assert(!std::is_constructible_v<Imos<ExplicitAddSum>, std::forward_list<int>&>);
static_assert(!std::is_constructible_v<MonoidUnionFind<ExplicitSum>, const std::vector<std::string>&>);
MonoidUnionFind uf(std::vector<int>{2, -5, 4}, ExplicitSum{});
uf.merge(0, 1);
check(uf.prod(0).value == -3 && uf.prod(2).value == 4, "MonoidUnionFind conversion / CTAD");
MonoidUnionFind<ExplicitSum> empty(std::vector<int>{});
check(empty.groups().empty(), "MonoidUnionFind conversion empty");
Imos imos(std::vector<int>{2, -5, 4}, ExplicitAddSum{});
imos.apply(0, 2, 3);
check(imos.get(0).value == 5 && imos.get(1).value == -2 && imos.get(2).value == 4, "Imos conversion / CTAD");
Imos<ExplicitAddSum> empty_imos(std::vector<int>{});
static_assert(!std::is_constructible_v<Imos<ExplicitAddSum>, const std::vector<std::string>&>);
}
test_converting_tree<LazySegTree>(ExplicitAddSum{});
test_converting_tree<DualSegTree>(ExplicitAddSum{});
test_converting_tree<PersistentSegTree>(ExplicitSum{});
test_converting_tree<PersistentLazySegTree>(ExplicitAddSum{});
test_converting_tree<SegTreeBeats>(ExplicitBeats{});
{
auto verify = [](auto&& keys, auto&& values) {
SortableSegTree tree(std::forward<decltype(keys)>(keys), std::forward<decltype(values)>(values), 3, ExplicitSum{});
tree.sort(0, 3);
check(tree.prod(0, 1).value == -5 && tree.prod(0, 3).value == 1, "SortableSegTree sized ranges / sort / CTAD");
};
int keys[] = {2, 0, 1};
verify(keys, std::list<int>{2, -5, 4});
verify(std::list<int>{2, 0, 1}, SizedInputRange{});
SortableSegTree braces({2, 0, 1}, {ExplicitSum::S(2), ExplicitSum::S(-5), ExplicitSum::S(4)}, 3, ExplicitSum{});
check(braces.prod(0, 3).value == 1, "SortableSegTree initializer lists / CTAD");
SortableSegTree sorted(std::vector<long long>{2, 0, 1}, std::vector<int>{2, -5, 4}, 3, ExplicitSum{});
sorted.sort(0, 3);
check(sorted.prod(0, 1).value == -5 && sorted.prod(0, 3).value == 1, "SortableSegTree conversion / CTAD / sort");
SortableSegTree<ExplicitSum> empty(std::vector<long long>{}, std::vector<int>{}, 1);
check(empty.size() == 0, "SortableSegTree conversion empty");
}
{
static_assert(std::is_constructible_v<SegTree<ExplicitSum>, const std::vector<int>&>);
static_assert(!std::is_constructible_v<SegTree<ExplicitSum>, const std::vector<std::string>&>);
SegTree seg(std::vector<int>{2, -5, 4}, ExplicitSum{});
check(seg.prod(0, 3).value == 1 && seg.prod(1, 3).value == -1, "SegTree explicit conversion / CTAD");
SegTree<ExplicitSum> empty(std::vector<int>{});
check(empty.size() == 0 && empty.all_prod().value == 0, "SegTree conversion empty");
SegTree<monoid::Sum<long long>> ordinary({1, 2, 3});
check(ordinary.all_prod() == 6, "SegTree initializer list");
SegTree<monoid::Sum<long long>> widened(std::vector<int>{1, 2, 3});
check(widened.all_prod() == 6, "SegTree arithmetic conversion");
}
{
using PC = MaxCounter<int, 3>;
using M = monoid::Sum<PC>;
static_assert(M::e().size() == 0);
static_assert(group::Sum<long long>::e() == 0);
SegTree<M> empty(3);
check(empty.all_prod().size() == 0, "Sum<PriorityCounter> 初期値は空");
SegTree<M> seg(std::vector<int>{-5, -5, -2});
const std::vector<int> values = {-5, -5, -2};
for (long long l = 0; l <= 3; l++) {
for (long long r = l; r <= 3; r++) {
PC expect;
for (long long i = l; i < r; i++) expect.inc(values[i]);
const auto actual = seg.prod(l, r);
check(actual.size() == expect.size(), "Sum<PriorityCounter> 種類数");
for (long long i = 0; i < 3; i++) {
check(actual[i].second == expect[i].second, "Sum<PriorityCounter> 個数");
if (expect[i].second) check(actual[i].first == expect[i].first, "Sum<PriorityCounter> 値");
}
}
}
}
std::mt19937_64 rng(314);
// And / Or: 単位元はそれぞれ全ビット 1 と 0
check(monoid::And<unsigned>::e() == ~0u, "And::e");
check(monoid::Or<unsigned>::e() == 0u, "Or::e");
auto gen_bits = [&] { return static_cast<unsigned>(rng() % 64); };
test_segtree<monoid::And<unsigned>>([](unsigned a, unsigned b) { return a & b; }, ~0u, gen_bits, rng, "And");
test_segtree<monoid::Or<unsigned>>([](unsigned a, unsigned b) { return a | b; }, 0u, gen_bits, rng, "Or");
// Parenthesis: 区間が正しい括弧列かを is_valid で判定する
for (int rep = 0; rep < 300 && ok; rep++) {
int n = rng() % 16 + 1;
std::string s(n, '(');
for (char& c : s) c = rng() % 2 ? '(' : ')';
SegTree<monoid::Parenthesis> seg(s);
for (int l = 0; l <= n; l++) {
for (int r = l; r <= n; r++) {
int depth = 0, min_depth = 0;
for (int i = l; i < r; i++) {
depth += s[i] == '(' ? 1 : -1;
min_depth = std::min(min_depth, depth);
}
auto p = seg.prod(l, r);
check(p.is_valid() == (depth == 0 && min_depth == 0), "Parenthesis::is_valid");
check(p.close == -min_depth && p.open == depth - min_depth, "Parenthesis::op");
}
}
}
// Affine: ==, !=, 出力
{
Affine<long long> f{2, 3}, g{2, 3}, h{2, 4}, id;
check(f == g && !(f != g), "Affine ==");
check(f != h && !(f == h), "Affine !=");
check(id == Affine<long long>{1, 0}, "Affine default");
std::ostringstream os;
os << f;
check(os.str() == "2 3", "Affine <<");
// Composite で合成した結果が関数の合成 a∘b と一致する。Reverse は b∘a
for (int rep = 0; rep < 1000 && ok; rep++) {
Affine<long long> a{static_cast<long long>(rng() % 7) - 3, static_cast<long long>(rng() % 7) - 3};
Affine<long long> b{static_cast<long long>(rng() % 7) - 3, static_cast<long long>(rng() % 7) - 3};
long long x = static_cast<long long>(rng() % 7) - 3;
auto c = monoid::Composite<long long>::op(a, b);
check(c(x) == a(b(x)), "Composite op");
check(c == Affine<long long>{a.a * b.a, a.a * b.b + a.b}, "Affine == after op");
auto d = monoid::Reverse<monoid::Composite<long long>>().op(a, b);
check(d(x) == b(a(x)), "Reverse<Composite> op");
}
}
// Clamp: ==, !=, 入出力, 既定値は恒等写像
{
Clamp<long long> f{2, 5}, g{2, 5}, h{2, 6}, id;
check(f == g && !(f != g), "Clamp ==");
check(f != h && !(f == h), "Clamp !=");
check(id(std::numeric_limits<long long>::lowest()) == std::numeric_limits<long long>::lowest() && id(std::numeric_limits<long long>::max()) == std::numeric_limits<long long>::max(), "Clamp default");
check(f(1) == 2 && f(3) == 3 && f(9) == 5, "Clamp ()");
// {} を渡すと下限・上限なし。1 つの値からは暗黙に変換しない
check((Clamp<long long>{0, {}} == Clamp<long long>{0, std::numeric_limits<long long>::max()}), "Clamp {lb, {}}");
check((Clamp<long long>{{}, 0} == Clamp<long long>{std::numeric_limits<long long>::lowest(), 0}), "Clamp {{}, ub}");
check((Clamp<long long>{{}, {}} == Clamp<long long>{}), "Clamp {{}, {}}");
static_assert(!std::is_convertible_v<long long, Clamp<long long>>);
static_assert(std::is_trivially_copyable_v<Clamp<long long>>);
static_assert(Clamp<int>{0, {}}(-5) == 0);
std::ostringstream os;
os << f;
check(os.str() == "2 5", "Clamp <<");
std::istringstream is("-3 4");
is >> f;
check(f == Clamp<long long>{-3, 4}, "Clamp >>");
// ClampComposite で合成した結果が関数の合成 a∘b と一致する。Reverse は b∘a
auto gen_clamp = [&] {
long long lb = static_cast<long long>(rng() % 11) - 5, ub = static_cast<long long>(rng() % 11) - 5;
if (lb > ub) std::swap(lb, ub);
if (rng() % 4 == 0) lb = std::numeric_limits<long long>::lowest();
if (rng() % 4 == 0) ub = std::numeric_limits<long long>::max();
return Clamp<long long>{lb, ub};
};
for (int rep = 0; rep < 1000 && ok; rep++) {
auto a = gen_clamp(), b = gen_clamp();
auto c = monoid::ClampComposite<long long>::op(a, b);
auto d = monoid::Reverse<monoid::ClampComposite<long long>>().op(a, b);
check(c.lb <= c.ub, "ClampComposite lb <= ub");
check(monoid::ClampComposite<long long>::op(a, monoid::ClampComposite<long long>::e()) == a, "ClampComposite e");
check(monoid::ClampComposite<long long>::op(monoid::ClampComposite<long long>::e(), a) == a, "ClampComposite e");
for (long long x = -7; x <= 7; x++) {
check(c(x) == a(b(x)), "ClampComposite op");
check(d(x) == b(a(x)), "Reverse<ClampComposite> op");
}
}
// SegTree に乗せて、区間の関数を右から順に適用した結果と比べる
test_segtree<monoid::ClampComposite<long long>>(
[](const Clamp<long long>& a, const Clamp<long long>& b) { return monoid::ClampComposite<long long>::op(a, b); },
Clamp<long long>{}, gen_clamp, rng, "ClampComposite");
}
// ClampAdd: ==, !=, 入出力, 既定値は恒等写像
{
constexpr long long lowest = std::numeric_limits<long long>::lowest(), highest = std::numeric_limits<long long>::max();
ClampAdd<long long> f{2, 5, 1}, g{2, 5, 1}, h{2, 5, 0}, id;
check(f == g && !(f != g), "ClampAdd ==");
check(f != h && !(f == h), "ClampAdd !=");
check(id == ClampAdd<long long>{lowest, highest, 0} && id(lowest) == lowest && id(highest) == highest, "ClampAdd default");
check(f(0) == 2 && f(2) == 3 && f(9) == 5, "ClampAdd ()");
// {} を渡すと下限・上限なし。add は省略すると 0。1 つの値からは暗黙に変換しない
check((ClampAdd<long long>{{}, {}, 3} == ClampAdd<long long>{lowest, highest, 3}), "ClampAdd {{}, {}, add}");
check((ClampAdd<long long>{{}, 5} == ClampAdd<long long>{lowest, 5, 0}), "ClampAdd {{}, ub}");
check((ClampAdd<long long>{5, {}} == ClampAdd<long long>{5, highest, 0}), "ClampAdd {lb, {}}");
static_assert(!std::is_convertible_v<long long, ClampAdd<long long>>);
static_assert(std::is_trivially_copyable_v<ClampAdd<long long>>);
static_assert(ClampAdd<int>{{}, 10, 3}(9) == 10);
std::ostringstream os;
os << f;
check(os.str() == "2 5 1", "ClampAdd <<");
std::istringstream is("-3 4 -1");
is >> f;
check(f == ClampAdd<long long>{-3, 4, -1}, "ClampAdd >>");
// ClampAddComposite で合成した結果が関数の合成 a∘b と一致する。Reverse は b∘a
// 下限・上限なし (型の最小値・最大値) に足してもあふれない (UBSan で確かめる)
auto gen_clamp_add = [&] {
long long lb = static_cast<long long>(rng() % 11) - 5, ub = static_cast<long long>(rng() % 11) - 5;
if (lb > ub) std::swap(lb, ub);
if (rng() % 3 == 0) lb = lowest;
if (rng() % 3 == 0) ub = highest;
return ClampAdd<long long>{lb, ub, static_cast<long long>(rng() % 7) - 3};
};
for (int rep = 0; rep < 1000 && ok; rep++) {
auto a = gen_clamp_add(), b = gen_clamp_add();
auto c = monoid::ClampAddComposite<long long>::op(a, b);
auto d = monoid::Reverse<monoid::ClampAddComposite<long long>>().op(a, b);
check(c.lb <= c.ub, "ClampAddComposite lb <= ub");
check(monoid::ClampAddComposite<long long>::op(a, monoid::ClampAddComposite<long long>::e()) == a, "ClampAddComposite e");
check(monoid::ClampAddComposite<long long>::op(monoid::ClampAddComposite<long long>::e(), a) == a, "ClampAddComposite e");
for (long long x = -9; x <= 9; x++) {
check(c(x) == a(b(x)), "ClampAddComposite op");
check(d(x) == b(a(x)), "Reverse<ClampAddComposite> op");
}
}
// SegTree に乗せる (加算が積み重なってもあふれない範囲で)
test_segtree<monoid::ClampAddComposite<long long>>(
[](const ClampAdd<long long>& a, const ClampAdd<long long>& b) { return monoid::ClampAddComposite<long long>::op(a, b); },
ClampAdd<long long>{}, gen_clamp_add, rng, "ClampAddComposite");
}
// group::Xor: inv は自分自身。PotentializedUnionFind に乗せて xor のポテンシャルと比べる
for (int rep = 0; rep < 300 && ok; rep++) {
int n = rng() % 12 + 1;
std::vector<int> pot(n);
for (int& p : pot) p = rng() % 1024;
std::vector<int> comp(n);
for (int i = 0; i < n; i++) comp[i] = i;
PotentializedUnionFind<group::Xor<int>> uf(n);
for (int q = 0; q < 30 && ok; q++) {
int a = rng() % n, b = rng() % n;
if (rng() % 2) {
uf.merge(a, b, pot[a] ^ pot[b]);
int ca = comp[a], cb = comp[b];
for (int& c : comp)
if (c == cb) c = ca;
} else {
check(uf.same(a, b) == (comp[a] == comp[b]), "group::Xor same");
if (comp[a] == comp[b]) check(uf.diff(a, b) == (pot[a] ^ pot[b]), "group::Xor diff");
}
}
int x = rng() % 1024;
check(group::Xor<int>::inv(x) == x, "group::Xor::inv");
}
// PrefixSumMax / PrefixSumMin / PrefixSumMinMax / SuffixSumMax / SuffixSumMin / MaxSubarraySum: 空を含む prefix・suffix・部分配列の和
for (int rep = 0; rep < 300 && ok; rep++) {
int n = rng() % 12 + 1;
std::vector<long long> a(n);
for (auto& x : a) x = static_cast<long long>(rng() % 21) - 10;
SegTree<monoid::PrefixSumMax<long long>> pmax(a);
SegTree<monoid::PrefixSumMin<long long>> pmin(a);
using PM = monoid::PrefixSumMinMax<>;
SegTree<PM> pminmax(a);
SegTree<monoid::SuffixSumMax<long long>> smax(a);
SegTree<monoid::SuffixSumMin<long long>> smin(a);
SegTree<monoid::MaxSubarraySum<long long>> msub(a);
for (int q = 0; q < 10 && ok; q++) {
int k = rng() % n;
a[k] = static_cast<long long>(rng() % 21) - 10;
pminmax.set(k, a[k]);
pmax.set(k, a[k]), pmin.set(k, a[k]), smax.set(k, a[k]), smin.set(k, a[k]), msub.set(k, a[k]);
for (int l = 0; l <= n; l++) {
for (int r = l; r <= n; r++) {
long long sum = 0, pre_max = 0, pre_min = 0, suf_max = 0, suf_min = 0, best = 0;
for (int i = l; i < r; i++) {
sum += a[i];
pre_max = std::max(pre_max, sum), pre_min = std::min(pre_min, sum);
long long s = 0;
for (int j = i; j < r; j++) {
s += a[j];
best = std::max(best, s);
}
}
long long s = 0;
for (int i = r - 1; i >= l; i--) {
s += a[i];
suf_max = std::max(suf_max, s), suf_min = std::min(suf_min, s);
}
check(pmax.prod(l, r) == monoid::PrefixSumMax<long long>::S(sum, pre_max), "PrefixSumMax");
check(pmin.prod(l, r) == monoid::PrefixSumMin<long long>::S(sum, pre_min), "PrefixSumMin");
check(pminmax.prod(l, r) == PM::S(sum, pre_min, pre_max), "PrefixSumMinMax");
check(PM::op(PM::e(), pminmax.prod(l, r)) == pminmax.prod(l, r) &&
PM::op(pminmax.prod(l, r), PM::e()) == pminmax.prod(l, r),
"PrefixSumMinMax identity");
int m = (l + r) / 2;
check(PM::op(pminmax.prod(l, m), pminmax.prod(m, r)) == pminmax.prod(l, r), "PrefixSumMinMax concatenate");
check(smax.prod(l, r) == monoid::SuffixSumMax<long long>::S(sum, suf_max), "SuffixSumMax");
check(smin.prod(l, r) == monoid::SuffixSumMin<long long>::S(sum, suf_min), "SuffixSumMin");
check(msub.prod(l, r) == monoid::MaxSubarraySum<long long>::S(sum, pre_max, suf_max, best), "MaxSubarraySum");
}
}
// max_right: l から始めて和が初めて正になる位置
int l = rng() % (n + 1);
long long sum = 0;
int expect = n;
for (int i = l; i < n; i++) {
sum += a[i];
if (sum > 0) {
expect = i;
break;
}
}
check(pmax.max_right(l, [](const auto& s) { return s.max <= 0; }) == expect, "PrefixSumMax max_right");
}
}
// MinWith / MaxWith: 空区間は位置 -1。値が型の最大値 (最小値) の要素があっても単位元として働き、同じ値なら左側
{
using Mn = monoid::MinWith<long long>;
using Mx = monoid::MaxWith<long long>;
constexpr long long INF = std::numeric_limits<long long>::max(), NINF = std::numeric_limits<long long>::lowest();
check(Mn::e() == std::pair<long long, long long>(INF, -1) && Mx::e() == std::pair<long long, long long>(NINF, -1), "MinWith/MaxWith::e");
check(Mn::op(Mn::e(), {INF, 3}) == std::pair<long long, long long>(INF, 3) && Mn::op({INF, 3}, Mn::e()) == std::pair<long long, long long>(INF, 3), "MinWith e は単位元");
check(Mx::op(Mx::e(), {NINF, 3}) == std::pair<long long, long long>(NINF, 3) && Mx::op({NINF, 3}, Mx::e()) == std::pair<long long, long long>(NINF, 3), "MaxWith e は単位元");
for (int rep = 0; rep < 200 && ok; rep++) {
int n = rng() % 20 + 1;
std::vector<long long> a(n);
for (auto& x : a) x = rng() % 3 == 0 ? (rng() % 2 ? INF : NINF) : static_cast<long long>(rng() % 5);
std::vector<std::pair<long long, long long>> init(n);
for (int i = 0; i < n; i++) init[i] = {a[i], i};
SegTree<Mn> mn(init);
SegTree<Mx> mx(init);
for (int q = 0; q < 30; q++) {
int l = rng() % (n + 1), r = rng() % (n + 1);
if (l > r) std::swap(l, r);
std::pair<long long, long long> emn(INF, -1), emx(NINF, -1);
for (int i = l; i < r; i++) {
if (emn.second == -1 || a[i] < emn.first) emn = {a[i], i};
if (emx.second == -1 || a[i] > emx.first) emx = {a[i], i};
}
check(mn.prod(l, r) == emn, "MinWith prod");
check(mx.prod(l, r) == emx, "MaxWith prod");
}
}
}
if (ok) std::cout << "Hello World" << std::endl;
}