#line 1 "verify/ds/persistent_cow.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"
#line 1 "acted_monoid/range_add_range_sum.hpp"
namespacem1une{namespaceacted_monoid{template<typenameT>structRangeAddRangeSumNode{Tsum;longlongsize;};template<typenameT>structRangeAddRangeSum{usingvalue_type=RangeAddRangeSumNode<T>;usingoperator_type=T;staticconstexprboolcommutative=true;staticconstexprbooloperator_commutative=true;// Value Monoid (Sum)staticconstexprvalue_typeid(){return{T(0),0};}staticconstexprvalue_typeop(constvalue_type&a,constvalue_type&b){return{a.sum+b.sum,a.size+b.size};}staticconstexprvalue_typeinv(constvalue_type&x){return{-x.sum,-x.size};}// Operator Monoid (Add)staticconstexproperator_typeop_id(){return0;}staticconstexproperator_typeop_comp(constoperator_type&f,constoperator_type&g){returnf+g;}// Mapping (sum + f * size)staticconstexprvalue_typemapping(constoperator_type&f,constvalue_type&x){return{x.sum+f*x.size,x.size};}// Helper for initializing a leaf nodestaticconstexprvalue_typemake(constT&val){return{val,1};}};}// namespace acted_monoid}// namespace m1une#line 1 "ds/dsu/persistent_dsu.hpp"
#include<algorithm>
#include<cassert>
#include<cstddef>
#include<memory>
#include<utility>
#include<vector>#line 1 "ds/detail/persistent_binary_node_pool.hpp"
#line 6 "ds/detail/persistent_binary_node_pool.hpp"
#include<deque>
#include<limits>
#include<optional>
#line 11 "ds/detail/persistent_binary_node_pool.hpp"
namespacem1une{namespaceds{namespacedetail{// Node must have integer `l` and `r` members. New nodes initially have no// owner; discard_unreferenced() removes temporary path-copy nodes after the// result roots have been retained.template<classNode,intnull_node=-1>structPersistentBinaryNodePool{private:std::deque<std::optional<Node>>_nodes;std::vector<int>_references;std::vector<int>_next_free;std::vector<int>_unowned;int_first_free=-1;std::size_t_live_nodes=0;voidrelease_zero(intnode){assert(node!=null_node&&_nodes[node].has_value());intleft=(*_nodes[node]).l;intright=(*_nodes[node]).r;_nodes[node].reset();_next_free[node]=_first_free;_first_free=node;--_live_nodes;if(left!=null_node&&--_references[left]==0)release_zero(left);if(right!=null_node&&--_references[right]==0)release_zero(right);}public:PersistentBinaryNodePool(){ifconstexpr(null_node==0){_nodes.emplace_back();_references.push_back(0);_next_free.push_back(-1);}}Node&operator[](intnode){assert(node!=null_node&&_nodes[node].has_value());return*_nodes[node];}constNode&operator[](intnode)const{assert(node!=null_node&&_nodes[node].has_value());return*_nodes[node];}template<class...Args>intemplace(Args&&...args){intresult;if(_first_free==-1){assert(_nodes.size()<std::size_t(std::numeric_limits<int>::max()));result=int(_nodes.size());_nodes.emplace_back(std::in_place,std::forward<Args>(args)...);_references.push_back(0);_next_free.push_back(-1);}else{result=_first_free;_first_free=_next_free[result];_nodes[result].emplace(std::forward<Args>(args)...);_references[result]=0;}retain((*_nodes[result]).l);retain((*_nodes[result]).r);_unowned.push_back(result);++_live_nodes;returnresult;}voidretain(intnode){if(node!=null_node){assert(_nodes[node].has_value());++_references[node];}}voidrelease(intnode){if(node==null_node)return;assert(_nodes[node].has_value()&&_references[node]>0);if(--_references[node]==0)release_zero(node);}boolunique(intnode)const{returnnode==null_node||_references[node]==1;}intclone(intnode){assert(node!=null_node&&_nodes[node].has_value());returnemplace(*_nodes[node]);}// Returns node itself when it has one owner, otherwise an unowned clone.// A returned clone becomes owned when a root or parent edge retains it.intclone_if_shared(intnode){if(unique(node))returnnode;returnclone(node);}voidreplace(int&edge,intnode){if(edge==node)return;retain(node);intold=edge;edge=node;release(old);}voiddiscard_unreferenced(){while(!_unowned.empty()){intnode=_unowned.back();_unowned.pop_back();if(_nodes[node].has_value()&&_references[node]==0)release_zero(node);}}voidreserve(std::size_t){}intnext_index()const{return_first_free==-1?int(_nodes.size()):_first_free;}std::size_tsize()const{return_live_nodes;}};}// namespace detail}// namespace ds}// namespace m1une#line 12 "ds/dsu/persistent_dsu.hpp"
namespacem1une{namespaceds{structPersistentDsu{private:structNode{intval;intl,r;Node():val(0),l(0),r(0){}explicitNode(intvalue):val(value),l(0),r(0){}Node(intvalue,intleft,intright):val(value),l(left),r(right){}};int_n;int_root;usingPool=detail::PersistentBinaryNodePool<Node,0>;std::shared_ptr<Pool>_pool;explicitPersistentDsu(intn,introot,std::shared_ptr<Pool>pool):_n(n),_root(root),_pool(std::move(pool)){_pool->retain(_root);}intnew_node(constNode&node)const{return_pool->emplace(node);}intnew_node(Node&&node)const{return_pool->emplace(std::move(node));}intbuild(intl,intr)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(-1));intm=(l+r)>>1;intleft=build(l,m);intright=build(m,r);returnnew_node(Node(0,left,right));}intset_node(intt,intl,intr,intp,intvalue,boolcopy_on_write=false)const{if(copy_on_write)t=_pool->clone_if_shared(t);if(r-l==1){if(copy_on_write){(*_pool)[t].val=value;returnt;}returnnew_node(Node(value));}intm=(l+r)>>1;intleft=(*_pool)[t].l;intright=(*_pool)[t].r;if(p<m){left=set_node(left,l,m,p,value,copy_on_write);}else{right=set_node(right,m,r,p,value,copy_on_write);}if(copy_on_write){_pool->replace((*_pool)[t].l,left);_pool->replace((*_pool)[t].r,right);returnt;}returnnew_node(Node(0,left,right));}PersistentDsumake_version(introot)const{PersistentDsuresult(_n,root,_pool);_pool->discard_unreferenced();returnresult;}intget_node(intt,intl,intr,intp)const{while(r-l>1){intm=(l+r)>>1;if(p<m){t=(*_pool)[t].l;r=m;}else{t=(*_pool)[t].r;l=m;}}return(*_pool)[t].val;}public:PersistentDsu():PersistentDsu(0){}explicitPersistentDsu(intn):_n(n),_root(0),_pool(std::make_shared<Pool>()){assert(0<=n);_pool->reserve(n*2+1);if(_n>0)_root=build(0,_n);_pool->retain(_root);_pool->discard_unreferenced();}PersistentDsu(constPersistentDsu&other):_n(other._n),_root(other._root),_pool(other._pool){if(_pool)_pool->retain(_root);}PersistentDsu(PersistentDsu&&other)noexcept:_n(other._n),_root(other._root),_pool(std::move(other._pool)){other._n=0;other._root=0;}PersistentDsu&operator=(constPersistentDsu&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=other._pool;return*this;}PersistentDsu&operator=(PersistentDsu&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=std::move(other._pool);other._n=0;other._root=0;return*this;}~PersistentDsu(){if(_pool)_pool->release(_root);}intsize()const{return_n;}boolempty()const{return_n==0;}voidrelease(){if(_pool)_pool->release(_root);_n=0;_root=0;_pool=std::make_shared<Pool>();}std::size_tnode_count()const{return_pool?_pool->size():0;}intleader(inta)const{assert(0<=a&&a<_n);intx=a;intp=get(x);while(p>=0){x=p;p=get(x);}returnx;}boolsame(inta,intb)const{assert(0<=a&&a<_n);assert(0<=b&&b<_n);returnleader(a)==leader(b);}intgroup_size(inta)const{assert(0<=a&&a<_n);return-get(leader(a));}intsize(inta)const{returngroup_size(a);}intget(intp)const{assert(0<=p&&p<_n);returnget_node(_root,0,_n,p);}PersistentDsumerge(inta,intb)const{assert(0<=a&&a<_n);assert(0<=b&&b<_n);intx=leader(a),y=leader(b);if(x==y)return*this;intsx=-get(x),sy=-get(y);if(sx<sy){std::swap(x,y);std::swap(sx,sy);}introot=set_node(_root,0,_n,x,-(sx+sy));root=set_node(root,0,_n,y,x);returnmake_version(root);}boolmerge_inplace(inta,intb){assert(0<=a&&a<_n);assert(0<=b&&b<_n);intx=leader(a),y=leader(b);if(x==y)returnfalse;intsx=-get(x),sy=-get(y);if(sx<sy){std::swap(x,y);std::swap(sx,sy);}introot=set_node(_root,0,_n,x,-(sx+sy),true);_pool->replace(_root,root);root=set_node(_root,0,_n,y,x,true);_pool->replace(_root,root);_pool->discard_unreferenced();returntrue;}std::vector<std::vector<int>>groups()const{std::vector<int>leader_buf(_n),group_size(_n);for(inti=0;i<_n;i++){leader_buf[i]=leader(i);group_size[leader_buf[i]]++;}std::vector<std::vector<int>>result(_n);for(inti=0;i<_n;i++){result[i].reserve(group_size[i]);}for(inti=0;i<_n;i++){result[leader_buf[i]].push_back(i);}result.erase(std::remove_if(result.begin(),result.end(),[&](conststd::vector<int>&v){returnv.empty();}),result.end());returnresult;}};}// namespace ds}// namespace m1une#line 1 "ds/dsu/persistent_potentialized_dsu.hpp"
#line 6 "ds/dsu/persistent_potentialized_dsu.hpp"
#include<concepts>
#line 11 "ds/dsu/persistent_potentialized_dsu.hpp"
#line 1 "monoid/concept.hpp"
#line 5 "monoid/concept.hpp"
namespacem1une{namespacemonoid{// Concept to check if a type satisfies the requirements of a Monoid.// A Monoid must have a `value_type`, an identity element `id()`, and an associative binary operation `op()`.template<typenameM>conceptIsMonoid=requires(typenameM::value_typea,typenameM::value_typeb){// 1. Must define `value_type`typenameM::value_type;// 2. Must have a static method `id()` returning `value_type`{M::id()}->std::same_as<typenameM::value_type>;// 3. Must have a static method `op(a, b)` returning `value_type`{M::op(a,b)}->std::same_as<typenameM::value_type>;};// Concept for groups. A type satisfying this concept must also obey the group// laws; concepts can check the interface but not the algebraic properties.template<typenameM>conceptIsGroup=IsMonoid<M>&&requires(typenameM::value_typea){{M::inv(a)}->std::same_as<typenameM::value_type>;};// Concept for commutative groups. Commutativity is a semantic requirement and// cannot be checked by a C++ concept.template<typenameM>conceptIsCommutativeGroup=IsGroup<M>;}// namespace monoid}// namespace m1une#line 14 "ds/dsu/persistent_potentialized_dsu.hpp"
namespacem1une{namespaceds{template<m1une::monoid::IsGroupGroup>requiresstd::equality_comparable<typenameGroup::value_type>structPersistentPotentializedDsu{usingT=typenameGroup::value_type;structValue{intparent_or_size;Tdiff_to_parent;Value():parent_or_size(0),diff_to_parent(Group::id()){}Value(intparent_or_size_,constT&diff_to_parent_):parent_or_size(parent_or_size_),diff_to_parent(diff_to_parent_){}Value(intparent_or_size_,T&&diff_to_parent_):parent_or_size(parent_or_size_),diff_to_parent(std::move(diff_to_parent_)){}};private:structNode{Valueval;intl,r;Node():val(),l(0),r(0){}explicitNode(constValue&value):val(value),l(0),r(0){}explicitNode(Value&&value):val(std::move(value)),l(0),r(0){}Node(constValue&value,intleft,intright):val(value),l(left),r(right){}Node(Value&&value,intleft,intright):val(std::move(value)),l(left),r(right){}};int_n;int_root;usingPool=detail::PersistentBinaryNodePool<Node,0>;std::shared_ptr<Pool>_pool;explicitPersistentPotentializedDsu(intn,introot,std::shared_ptr<Pool>pool):_n(n),_root(root),_pool(std::move(pool)){_pool->retain(_root);}intnew_node(constNode&node)const{return_pool->emplace(node);}intnew_node(Node&&node)const{return_pool->emplace(std::move(node));}intbuild(intl,intr)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(Value(-1,Group::id())));intm=(l+r)>>1;intleft=build(l,m);intright=build(m,r);returnnew_node(Node(Value(),left,right));}intset_node(intt,intl,intr,intp,Valuevalue,boolcopy_on_write=false)const{if(copy_on_write)t=_pool->clone_if_shared(t);if(r-l==1){if(copy_on_write){(*_pool)[t].val=std::move(value);returnt;}returnnew_node(Node(std::move(value)));}intm=(l+r)>>1;intleft=(*_pool)[t].l;intright=(*_pool)[t].r;if(p<m){left=set_node(left,l,m,p,std::move(value),copy_on_write);}else{right=set_node(right,m,r,p,std::move(value),copy_on_write);}if(copy_on_write){_pool->replace((*_pool)[t].l,left);_pool->replace((*_pool)[t].r,right);returnt;}returnnew_node(Node(Value(),left,right));}Valueget_value(intt,intl,intr,intp)const{while(r-l>1){intm=(l+r)>>1;if(p<m){t=(*_pool)[t].l;r=m;}else{t=(*_pool)[t].r;l=m;}}return(*_pool)[t].val;}std::pair<int,T>leader_and_potential(inta)const{Tres=Group::id();while(true){Valuecur=get(a);if(cur.parent_or_size<0)return{a,res};res=Group::op(cur.diff_to_parent,res);a=cur.parent_or_size;}}PersistentPotentializedDsumake_version(introot)const{PersistentPotentializedDsuresult(_n,root,_pool);_pool->discard_unreferenced();returnresult;}public:PersistentPotentializedDsu():PersistentPotentializedDsu(0){}explicitPersistentPotentializedDsu(intn):_n(n),_root(0),_pool(std::make_shared<Pool>()){assert(0<=n);_pool->reserve(n*4+1);if(_n>0)_root=build(0,_n);_pool->retain(_root);_pool->discard_unreferenced();}PersistentPotentializedDsu(constPersistentPotentializedDsu&other):_n(other._n),_root(other._root),_pool(other._pool){if(_pool)_pool->retain(_root);}PersistentPotentializedDsu(PersistentPotentializedDsu&&other)noexcept:_n(other._n),_root(other._root),_pool(std::move(other._pool)){other._n=0;other._root=0;}PersistentPotentializedDsu&operator=(constPersistentPotentializedDsu&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=other._pool;return*this;}PersistentPotentializedDsu&operator=(PersistentPotentializedDsu&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=std::move(other._pool);other._n=0;other._root=0;return*this;}~PersistentPotentializedDsu(){if(_pool)_pool->release(_root);}intsize()const{return_n;}boolempty()const{return_n==0;}voidrelease(){if(_pool)_pool->release(_root);_n=0;_root=0;_pool=std::make_shared<Pool>();}std::size_tnode_count()const{return_pool?_pool->size():0;}intleader(inta)const{assert(0<=a&&a<_n);returnleader_and_potential(a).first;}boolsame(inta,intb)const{assert(0<=a&&a<_n);assert(0<=b&&b<_n);returnleader(a)==leader(b);}intgroup_size(inta)const{assert(0<=a&&a<_n);return-get(leader(a)).parent_or_size;}intsize(inta)const{returngroup_size(a);}Tpotential(inta)const{assert(0<=a&&a<_n);returnleader_and_potential(a).second;}Tdiff(inta,intb)const{assert(same(a,b));returnGroup::op(Group::inv(potential(a)),potential(b));}Valueget(intp)const{assert(0<=p&&p<_n);returnget_value(_root,0,_n,p);}intparent_or_size(intp)const{returnget(p).parent_or_size;}std::pair<PersistentPotentializedDsu,bool>merge(inta,intb,constT&w)const{assert(0<=a&&a<_n);assert(0<=b&&b<_n);auto[x,pa]=leader_and_potential(a);auto[y,pb]=leader_and_potential(b);if(x==y)return{*this,Group::op(Group::inv(pa),pb)==w};intsx=-get(x).parent_or_size;intsy=-get(y).parent_or_size;Ty_from_x=Group::op(Group::op(pa,w),Group::inv(pb));if(sx<sy){std::swap(x,y);std::swap(sx,sy);y_from_x=Group::inv(y_from_x);}introot=set_node(_root,0,_n,x,Value(-(sx+sy),Group::id()));root=set_node(root,0,_n,y,Value(x,std::move(y_from_x)));return{make_version(root),true};}boolmerge_inplace(inta,intb,constT&w){assert(0<=a&&a<_n);assert(0<=b&&b<_n);auto[x,pa]=leader_and_potential(a);auto[y,pb]=leader_and_potential(b);if(x==y)returnGroup::op(Group::inv(pa),pb)==w;intsx=-get(x).parent_or_size;intsy=-get(y).parent_or_size;Ty_from_x=Group::op(Group::op(pa,w),Group::inv(pb));if(sx<sy){std::swap(x,y);std::swap(sx,sy);y_from_x=Group::inv(y_from_x);}introot=set_node(_root,0,_n,x,Value(-(sx+sy),Group::id()),true);_pool->replace(_root,root);root=set_node(_root,0,_n,y,Value(x,std::move(y_from_x)),true);_pool->replace(_root,root);_pool->discard_unreferenced();returntrue;}std::vector<std::vector<int>>groups()const{std::vector<int>leader_buf(_n),group_size(_n);for(inti=0;i<_n;i++){leader_buf[i]=leader(i);group_size[leader_buf[i]]++;}std::vector<std::vector<int>>result(_n);for(inti=0;i<_n;i++){result[i].reserve(group_size[i]);}for(inti=0;i<_n;i++){result[leader_buf[i]].push_back(i);}result.erase(std::remove_if(result.begin(),result.end(),[&](conststd::vector<int>&v){returnv.empty();}),result.end());returnresult;}};}// namespace ds}// namespace m1une#line 1 "ds/bst/persistent_ordered_multiset.hpp"
#line 6 "ds/bst/persistent_ordered_multiset.hpp"
#include<functional>
#include<initializer_list>
#line 10 "ds/bst/persistent_ordered_multiset.hpp"
#line 12 "ds/bst/persistent_ordered_multiset.hpp"
namespacem1une{namespaceds{template<typenameT,typenameCompare>structPersistentOrderedSet;template<typenameT,typenameCompare=std::less<T>>structPersistentOrderedMultiset{private:friendstructPersistentOrderedSet<T,Compare>;structNode{Tkey;intcount;intsize;intdistinct_size;intrank_color;intl;intr;intmin_leaf;intmax_leaf;Node(Tvalue,intmultiplicity,intmaximum):key(std::move(value)),count(multiplicity),size(multiplicity),distinct_size(1),rank_color(1),l(-1),r(-1),min_leaf(maximum),max_leaf(maximum){}Node(Tseparator,intsubtree_size,intleft_size,intunique_count,intnode_rank,intleft,intright,intminimum,intmaximum,boolis_black):key(std::move(separator)),count(left_size),size(subtree_size),distinct_size(unique_count),rank_color(node_rank*2+int(is_black)),l(left),r(right),min_leaf(minimum),max_leaf(maximum){}};usingPool=detail::PersistentBinaryNodePool<Node>;inlinestaticPoolpool;introot;Comparecomp;staticintsubtree_size(intt){returnt==-1?0:pool[t].size;}staticintsubtree_distinct_size(intt){returnt==-1?0:pool[t].distinct_size;}staticintnode_rank(intt){returnpool[t].rank_color>>1;}staticboolis_black(intt){return(pool[t].rank_color&1)!=0;}staticboolis_leaf(intt){returnpool[t].l==-1;}boolequal(constT&a,constT&b)const{return!comp(a,b)&&!comp(b,a);}staticintmake_leaf(Tkey,intcount){constintid=pool.next_index();returnpool.emplace(std::move(key),count,id);}staticintmake_node(intl,intr,boolblack){assert(l!=-1&&r!=-1);constintrank=node_rank(l)+int(is_black(l));assert(rank==node_rank(r)+int(is_black(r)));returnpool.emplace(pool[pool[l].max_leaf].key,subtree_size(l)+subtree_size(r),subtree_size(l),subtree_distinct_size(l)+subtree_distinct_size(r),rank,l,r,pool[l].min_leaf,pool[r].max_leaf,black);}staticintas_root(intt){if(t==-1||is_black(t))returnt;returnmake_node(pool[t].l,pool[t].r,true);}staticintmerge_sub(inta,intb){assert(a!=-1&&b!=-1);if(node_rank(a)<node_rank(b)){constNode&right=pool[b];intc=merge_sub(a,right.l);if(is_black(b)&&!is_black(c)&&!is_black(pool[c].l)){constNode&middle=pool[c];if(is_black(right.r)){returnmake_node(middle.l,make_node(middle.r,right.r,false),true);}constNode&far=pool[right.r];returnmake_node(make_node(middle.l,middle.r,true),make_node(far.l,far.r,true),false);}returnmake_node(c,right.r,is_black(b));}if(node_rank(a)>node_rank(b)){constNode&left=pool[a];intc=merge_sub(left.r,b);if(is_black(a)&&!is_black(c)&&!is_black(pool[c].r)){constNode&middle=pool[c];if(is_black(left.l)){returnmake_node(make_node(left.l,middle.l,false),middle.r,true);}constNode&far=pool[left.l];returnmake_node(make_node(far.l,far.r,true),make_node(middle.l,middle.r,true),false);}returnmake_node(left.l,c,is_black(a));}returnmake_node(a,b,false);}staticintmerge_nodes(inta,intb){if(a==-1||b==-1)returna==-1?b:a;returnas_root(merge_sub(as_root(a),as_root(b)));}std::pair<int,int>split_nodes(intt,constT&key)const{if(t==-1)return{-1,-1};constNode&node=pool[t];if(is_leaf(t))returncomp(node.key,key)?std::pair{t,-1}:std::pair{-1,t};if(comp(node.key,key)){auto[l,r]=split_nodes(node.r,key);return{merge_nodes(as_root(node.l),l),r};}auto[l,r]=split_nodes(node.l,key);return{l,merge_nodes(r,as_root(node.r))};}intchange_count_impl(intt,constT&key,intdelta,int&old_count)const{if(t==-1)return-1;constNode&node=pool[t];if(is_leaf(t)){if(!equal(node.key,key))returnt;old_count=node.count;returnnode.count+delta==0?t:make_leaf(node.key,node.count+delta);}intchild;if(!comp(node.key,key)){child=change_count_impl(node.l,key,delta,old_count);if(old_count==0||old_count+delta==0)returnt;returnmake_node(child,node.r,is_black(t));}child=change_count_impl(node.r,key,delta,old_count);if(old_count==0||old_count+delta==0)returnt;returnmake_node(node.l,child,is_black(t));}intchange_count_inplace(intt,constT&key,intdelta)const{t=pool.clone_if_shared(t);if(is_leaf(t)){assert(equal(pool[t].key,key));assert(pool[t].count+delta>0);pool[t].count+=delta;pool[t].size+=delta;returnt;}if(!comp(pool[t].key,key)){intchild=change_count_inplace(pool[t].l,key,delta);pool.replace(pool[t].l,child);}else{intchild=change_count_inplace(pool[t].r,key,delta);pool.replace(pool[t].r,child);}Node&node=pool[t];node.count=subtree_size(node.l);node.size=node.count+subtree_size(node.r);returnt;}intcount_impl(intt,constT&key)const{if(t==-1)return0;while(!is_leaf(t)){t=!comp(pool[t].key,key)?pool[t].l:pool[t].r;}returnequal(pool[t].key,key)?pool[t].count:0;}constT*kth_impl(intt,intk)const{while(!is_leaf(t)){constintleft_size=pool[t].count;if(k<left_size){t=pool[t].l;}else{k-=left_size;t=pool[t].r;}}return&pool[t].key;}intorder_of_key_impl(intt,constT&key,boolupper)const{intresult=0;while(t!=-1&&!is_leaf(t)){constNode&node=pool[t];constT&separator=node.key;constbooltake_left=upper?!comp(key,separator):comp(separator,key);if(take_left){result+=node.count;t=node.r;}else{t=node.l;}}if(t!=-1){constbooltake_leaf=upper?!comp(key,pool[t].key):comp(pool[t].key,key);if(take_leaf)result+=pool[t].count;}returnresult;}constT*lower_bound_impl(intt,constT&key,boolstrict)const{constT*result=nullptr;while(t!=-1){constNode&node=pool[t];if(is_leaf(t)){constboolcandidate=strict?comp(key,node.key):!comp(node.key,key);returncandidate?&node.key:result;}constT&separator=node.key;constboolgo_left=strict?comp(key,separator):!comp(separator,key);if(go_left){result=&pool[pool[node.r].min_leaf].key;t=node.l;}else{t=node.r;}}returnresult;}constT*max_less_impl(intt,constT&key,boolstrict)const{constT*result=nullptr;while(t!=-1){constNode&node=pool[t];if(is_leaf(t)){constboolcandidate=strict?comp(node.key,key):!comp(key,node.key);returncandidate?&node.key:result;}constT&separator=node.key;constbooltake_left=strict?comp(separator,key):!comp(key,separator);if(take_left){result=&separator;t=node.r;}else{t=node.l;}}returnresult;}staticvoiddump_impl(intt,std::vector<T>&result){if(t==-1)return;constNode&node=pool[t];if(is_leaf(t)){for(inti=0;i<node.count;++i)result.push_back(node.key);return;}dump_impl(node.l,result);dump_impl(node.r,result);}staticstd::pair<int,int>pop_min(intt){assert(t!=-1);constNode&node=pool[t];if(is_leaf(t))return{t,-1};auto[minimum,rest]=pop_min(node.l);return{minimum,merge_nodes(rest,as_root(node.r))};}PersistentOrderedMultiset(intnode,Comparecompare):root(node),comp(std::move(compare)){pool.retain(root);}PersistentOrderedMultisetmake_version(intnode)const{PersistentOrderedMultisetresult(node,comp);pool.discard_unreferenced();returnresult;}public:explicitPersistentOrderedMultiset(Comparecompare):root(-1),comp(std::move(compare)){}PersistentOrderedMultiset():PersistentOrderedMultiset(Compare()){}PersistentOrderedMultiset(std::initializer_list<T>init,Comparecompare=Compare()):PersistentOrderedMultiset(std::move(compare)){for(constT&x:init)*this=insert(x);}template<typenameIterator>PersistentOrderedMultiset(Iteratorfirst,Iteratorlast,Comparecompare=Compare()):PersistentOrderedMultiset(std::move(compare)){while(first!=last)*this=insert(*first++);}PersistentOrderedMultiset(constPersistentOrderedMultiset&other):root(other.root),comp(other.comp){pool.retain(root);}PersistentOrderedMultiset(PersistentOrderedMultiset&&other):root(other.root),comp(std::move(other.comp)){other.root=-1;}PersistentOrderedMultiset&operator=(constPersistentOrderedMultiset&other){if(this==&other)return*this;pool.retain(other.root);pool.release(root);root=other.root;comp=other.comp;return*this;}PersistentOrderedMultiset&operator=(PersistentOrderedMultiset&&other){if(this==&other)return*this;pool.release(root);root=other.root;comp=std::move(other.comp);other.root=-1;return*this;}~PersistentOrderedMultiset(){pool.release(root);}intsize()const{returnsubtree_size(root);}intunique_size()const{returnsubtree_distinct_size(root);}boolempty()const{returnroot==-1;}voidrelease(){pool.release(std::exchange(root,-1));}std::size_tnode_count()const{returnpool.size();}PersistentOrderedMultisetclear()const{returnmake_version(-1);}PersistentOrderedMultisetinsert(Tkey,intmultiplicity=1)const{assert(multiplicity>0);intold_count=0;constintchanged_root=change_count_impl(root,key,multiplicity,old_count);if(old_count!=0){returnmake_version(changed_root);}auto[l,r]=split_nodes(root,key);returnmake_version(merge_nodes(merge_nodes(l,make_leaf(std::move(key),multiplicity)),r));}voidinsert_inplace(Tkey,intmultiplicity=1){assert(multiplicity>0);if(!contains(key)){*this=insert(std::move(key),multiplicity);return;}intnext_root=change_count_inplace(root,key,multiplicity);pool.replace(root,next_root);pool.discard_unreferenced();}private:PersistentOrderedMultisetinsert_unique(Tkey)const{if(contains(key))return*this;auto[l,r]=split_nodes(root,key);returnmake_version(merge_nodes(merge_nodes(l,make_leaf(std::move(key),1)),r));}public:PersistentOrderedMultiseterase_one(constT&key)const{intold_count=0;constintchanged_root=change_count_impl(root,key,-1,old_count);if(old_count==0)return*this;if(old_count>1)returnmake_version(changed_root);auto[l,r]=split_nodes(root,key);auto[discarded,rest]=pop_min(r);assert(equal(pool[discarded].key,key));returnmake_version(merge_nodes(l,rest));}PersistentOrderedMultiseterase(constT&key)const{returnerase_one(key);}boolerase_one_inplace(constT&key){intold_count=count(key);if(old_count==0)returnfalse;if(old_count==1){*this=erase_one(key);returntrue;}intnext_root=change_count_inplace(root,key,-1);pool.replace(root,next_root);pool.discard_unreferenced();returntrue;}boolerase_inplace(constT&key){returnerase_one_inplace(key);}PersistentOrderedMultiseterase_all(constT&key)const{constintold_count=count(key);if(old_count==0)return*this;auto[l,r]=split_nodes(root,key);auto[discarded,rest]=pop_min(r);assert(equal(pool[discarded].key,key));returnmake_version(merge_nodes(l,rest));}boolerase_all_inplace(constT&key){if(!contains(key))returnfalse;*this=erase_all(key);returntrue;}boolcontains(constT&key)const{returncount(key)>0;}intcount(constT&key)const{returncount_impl(root,key);}constT*find_by_order(intk)const{assert(0<=k&&k<size());returnkth_impl(root,k);}Tkth(intk)const{return*find_by_order(k);}intorder_of_key(constT&key)const{returnorder_of_key_impl(root,key,false);}intcount_less(constT&key)const{returnorder_of_key(key);}intcount_less_equal(constT&key)const{returnorder_of_key_impl(root,key,true);}intcount_greater(constT&key)const{returnsize()-count_less_equal(key);}intcount_greater_equal(constT&key)const{returnsize()-count_less(key);}constT*lower_bound(constT&key)const{returnlower_bound_impl(root,key,false);}constT*upper_bound(constT&key)const{returnlower_bound_impl(root,key,true);}constT*min_ge(constT&key)const{returnlower_bound(key);}constT*min_gt(constT&key)const{returnupper_bound(key);}constT*max_le(constT&key)const{returnmax_less_impl(root,key,false);}constT*max_lt(constT&key)const{returnmax_less_impl(root,key,true);}constT*min()const{returnempty()?nullptr:&pool[pool[root].min_leaf].key;}constT*max()const{returnempty()?nullptr:&pool[pool[root].max_leaf].key;}std::pair<PersistentOrderedMultiset,PersistentOrderedMultiset>split(constT&key)const{auto[l,r]=split_nodes(root,key);PersistentOrderedMultisetleft(l,comp);PersistentOrderedMultisetright(r,comp);pool.discard_unreferenced();return{std::move(left),std::move(right)};}PersistentOrderedMultisetmerge(constPersistentOrderedMultiset&other)const{assert(empty()||other.empty()||comp(*max(),*other.min()));returnmake_version(merge_nodes(root,other.root));}std::vector<T>to_vector()const{std::vector<T>result;result.reserve(size());dump_impl(root,result);returnresult;}};}// namespace ds}// namespace m1une#line 1 "ds/dynamic_array/persistent_dynamic_array.hpp"
#line 5 "ds/dynamic_array/persistent_dynamic_array.hpp"
#include<chrono>
#line 7 "ds/dynamic_array/persistent_dynamic_array.hpp"
#include<cstdint>
#line 13 "ds/dynamic_array/persistent_dynamic_array.hpp"
#line 15 "ds/dynamic_array/persistent_dynamic_array.hpp"
namespacem1une{namespaceds{template<typenameT>structPersistentDynamicArray{private:structNode{Tval;intpriority;intcount;intl,r;boolrev;Node(Tvalue,intnode_priority,intnode_count,intleft,intright,boolreversed):val(std::move(value)),priority(node_priority),count(node_count),l(left),r(right),rev(reversed){}};structBuildNode{Tval;intpriority;intl,r;BuildNode(Tvalue,intnode_priority):val(std::move(value)),priority(node_priority),l(-1),r(-1){}};introot;std::uint32_trng_state;usingPool=detail::PersistentBinaryNodePool<Node>;std::shared_ptr<Pool>pool;intsubtree_size(intt)const{returnt==-1?0:(*pool)[t].count;}staticstd::uint32_tnext_state(std::uint32_tstate){state^=state<<13;state^=state>>17;state^=state<<5;returnstate==0?1:state;}staticintnext_priority(std::uint32_t&state){state=next_state(state);returnint(state);}intmake_node(Tval,intpriority,boolrev,intl,intr)const{intcount=1+subtree_size(l)+subtree_size(r);returnpool->emplace(std::move(val),priority,count,l,r,rev);}intreversed_node(intt)const{if(t==-1)return-1;constNode&node=(*pool)[t];returnmake_node(node.val,node.priority,!node.rev,node.l,node.r);}intpush(intt)const{if(t==-1||!(*pool)[t].rev)returnt;Nodenode=(*pool)[t];intl=reversed_node(node.r);intr=reversed_node(node.l);returnmake_node(std::move(node.val),node.priority,false,l,r);}intmerge(intl,intr)const{if(l==-1||r==-1)returnl==-1?r:l;if((*pool)[l].priority>(*pool)[r].priority){Nodenode=(*pool)[push(l)];intright=merge(node.r,r);returnmake_node(std::move(node.val),node.priority,false,node.l,right);}Nodenode=(*pool)[push(r)];intleft=merge(l,node.l);returnmake_node(std::move(node.val),node.priority,false,left,node.r);}std::pair<int,int>split_node(intt,intpos)const{if(t==-1)return{-1,-1};Nodenode=(*pool)[push(t)];intleft_count=subtree_size(node.l);if(pos<=left_count){auto[a,b]=split_node(node.l,pos);return{a,make_node(std::move(node.val),node.priority,false,b,node.r)};}auto[a,b]=split_node(node.r,pos-left_count-1);return{make_node(std::move(node.val),node.priority,false,node.l,a),b};}intset_node(intt,intpos,Tval)const{Nodenode=(*pool)[push(t)];intleft_count=subtree_size(node.l);if(pos<left_count){intl=set_node(node.l,pos,std::move(val));returnmake_node(std::move(node.val),node.priority,false,l,node.r);}if(pos==left_count){returnmake_node(std::move(val),node.priority,false,node.l,node.r);}intr=set_node(node.r,pos-left_count-1,std::move(val));returnmake_node(std::move(node.val),node.priority,false,node.l,r);}intset_node_inplace(intt,intpos,Tval,boolinherited_reversed=false)const{t=pool->clone_if_shared(t);constboolreversed=inherited_reversed^(*pool)[t].rev;constintlogical_left=reversed?(*pool)[t].r:(*pool)[t].l;constintleft_count=subtree_size(logical_left);if(pos<left_count){intchild=set_node_inplace(logical_left,pos,std::move(val),reversed);if(reversed){pool->replace((*pool)[t].r,child);}else{pool->replace((*pool)[t].l,child);}}elseif(pos==left_count){(*pool)[t].val=std::move(val);}else{constintlogical_right=reversed?(*pool)[t].l:(*pool)[t].r;intchild=set_node_inplace(logical_right,pos-left_count-1,std::move(val),reversed);if(reversed){pool->replace((*pool)[t].l,child);}else{pool->replace((*pool)[t].r,child);}}returnt;}intfind_node(intt,intpos)const{boolreversed=false;while(t!=-1){constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);if(pos<left_count){t=l;reversed=cur_reversed;}elseif(pos==left_count){returnt;}else{pos-=left_count+1;t=r;reversed=cur_reversed;}}return-1;}voiddump_dfs(intt,std::vector<T>&res,boolreversed=false)const{if(t==-1)return;constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;dump_dfs(l,res,cur_reversed);res.push_back(node.val);dump_dfs(r,res,cur_reversed);}voiddump_range_dfs(intt,intql,intqr,intoffset,std::vector<T>&res,boolreversed=false)const{if(t==-1||qr<=offset||offset+(*pool)[t].count<=ql)return;constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);intnode_pos=offset+left_count;dump_range_dfs(l,ql,qr,offset,res,cur_reversed);if(ql<=node_pos&&node_pos<qr)res.push_back(node.val);dump_range_dfs(r,ql,qr,node_pos+1,res,cur_reversed);}intbuild_from_nodes(std::vector<BuildNode>&nodes,intt)const{if(t==-1)return-1;intl=build_from_nodes(nodes,nodes[t].l);intr=build_from_nodes(nodes,nodes[t].r);returnmake_node(std::move(nodes[t].val),nodes[t].priority,false,l,r);}intbuild_cartesian(std::vector<BuildNode>&nodes)const{if(nodes.empty())return-1;std::vector<int>stack;stack.reserve(nodes.size());for(inti=0;i<int(nodes.size());i++){intleft_child=-1;while(!stack.empty()&&nodes[stack.back()].priority<nodes[i].priority){left_child=stack.back();stack.pop_back();}nodes[i].l=left_child;if(!stack.empty())nodes[stack.back()].r=i;stack.push_back(i);}returnbuild_from_nodes(nodes,stack.front());}intbuild_from_vector(conststd::vector<T>&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(constT&x:v)nodes.emplace_back(x,next_priority(state));returnbuild_cartesian(nodes);}intbuild_from_vector(std::vector<T>&&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(T&x:v)nodes.emplace_back(std::move(x),next_priority(state));returnbuild_cartesian(nodes);}intimport_node(constPersistentDynamicArray&other,intt)const{if(t==-1)return-1;if(pool==other.pool)returnt;constNode&node=(*other.pool)[t];intl=import_node(other,node.l);intr=import_node(other,node.r);returnmake_node(node.val,node.priority,node.rev,l,r);}explicitPersistentDynamicArray(intnode,std::uint32_tstate,std::shared_ptr<Pool>node_pool):root(node),rng_state(state),pool(std::move(node_pool)){pool->retain(root);}PersistentDynamicArraymake_version(intnode,std::uint32_tstate)const{PersistentDynamicArrayresult(node,state,pool);pool->discard_unreferenced();returnresult;}public:PersistentDynamicArray():root(-1),rng_state(std::uint32_t(std::chrono::steady_clock::now().time_since_epoch().count())),pool(std::make_shared<Pool>()){if(rng_state==0)rng_state=1;}explicitPersistentDynamicArray(intn):PersistentDynamicArray(n,T()){}PersistentDynamicArray(intn,constT&value):PersistentDynamicArray(){assert(0<=n);std::vector<T>v(n,value);root=build_from_vector(std::move(v),rng_state);pool->retain(root);pool->discard_unreferenced();}explicitPersistentDynamicArray(conststd::vector<T>&v):PersistentDynamicArray(){root=build_from_vector(v,rng_state);pool->retain(root);pool->discard_unreferenced();}explicitPersistentDynamicArray(std::vector<T>&&v):PersistentDynamicArray(){root=build_from_vector(std::move(v),rng_state);pool->retain(root);pool->discard_unreferenced();}PersistentDynamicArray(std::initializer_list<T>init):PersistentDynamicArray(std::vector<T>(init)){}PersistentDynamicArray(constPersistentDynamicArray&other):root(other.root),rng_state(other.rng_state),pool(other.pool){if(pool)pool->retain(root);}PersistentDynamicArray(PersistentDynamicArray&&other)noexcept:root(other.root),rng_state(other.rng_state),pool(std::move(other.pool)){other.root=-1;}PersistentDynamicArray&operator=(constPersistentDynamicArray&other){if(this==&other)return*this;if(other.pool)other.pool->retain(other.root);if(pool)pool->release(root);root=other.root;rng_state=other.rng_state;pool=other.pool;return*this;}PersistentDynamicArray&operator=(PersistentDynamicArray&&other)noexcept{if(this==&other)return*this;if(pool)pool->release(root);root=other.root;rng_state=other.rng_state;pool=std::move(other.pool);other.root=-1;return*this;}~PersistentDynamicArray(){if(pool)pool->release(root);}intsize()const{returnsubtree_size(root);}boolempty()const{returnsize()==0;}voidrelease(){if(pool)pool->release(root);root=-1;pool=std::make_shared<Pool>();}std::size_tnode_count()const{returnpool?pool->size():0;}PersistentDynamicArrayclear()const{returnmake_version(-1,rng_state);}PersistentDynamicArrayinsert(intpos,Tval)const{assert(0<=pos&&pos<=size());std::uint32_tnext=next_state(rng_state);intnode=make_node(std::move(val),int(next),false,-1,-1);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,node),r),next);}PersistentDynamicArrayinsert(intpos,conststd::vector<T>&v)const{assert(0<=pos&&pos<=size());if(v.empty())return*this;std::uint32_tnext=rng_state;intmid=build_from_vector(v,next);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),next);}PersistentDynamicArrayinsert(intpos,std::vector<T>&&v)const{assert(0<=pos&&pos<=size());if(v.empty())return*this;std::uint32_tnext=rng_state;intmid=build_from_vector(std::move(v),next);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),next);}PersistentDynamicArrayinsert(intpos,std::initializer_list<T>init)const{returninsert(pos,std::vector<T>(init));}PersistentDynamicArrayinsert(intpos,constPersistentDynamicArray&other)const{assert(0<=pos&&pos<=size());if(other.empty())return*this;intmid=import_node(other,other.root);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),rng_state);}PersistentDynamicArraypush_back(Tval)const{returninsert(size(),std::move(val));}PersistentDynamicArraypush_front(Tval)const{returninsert(0,std::move(val));}PersistentDynamicArrayappend(conststd::vector<T>&v)const{returninsert(size(),v);}PersistentDynamicArrayappend(std::vector<T>&&v)const{returninsert(size(),std::move(v));}PersistentDynamicArrayappend(constPersistentDynamicArray&other)const{returninsert(size(),other);}PersistentDynamicArrayerase(intpos)const{assert(0<=pos&&pos<size());auto[a,b]=split_node(root,pos);auto[mid,c]=split_node(b,1);(void)mid;returnmake_version(merge(a,c),rng_state);}PersistentDynamicArrayerase(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)return*this;auto[a,b]=split_node(root,l);auto[mid,c]=split_node(b,r-l);(void)mid;returnmake_version(merge(a,c),rng_state);}PersistentDynamicArraypop_back()const{assert(!empty());returnerase(size()-1);}PersistentDynamicArraypop_front()const{assert(!empty());returnerase(0);}constT&at(intpos)const{assert(0<=pos&&pos<size());return(*pool)[find_node(root,pos)].val;}constT&operator[](intpos)const{returnat(pos);}constT&front()const{assert(!empty());returnat(0);}constT&back()const{assert(!empty());returnat(size()-1);}Tget(intpos)const{returnat(pos);}PersistentDynamicArrayset(intpos,Tval)const{assert(0<=pos&&pos<size());returnmake_version(set_node(root,pos,std::move(val)),rng_state);}voidset_inplace(intpos,Tval){assert(0<=pos&&pos<size());intnext_root=set_node_inplace(root,pos,std::move(val));pool->replace(root,next_root);pool->discard_unreferenced();}PersistentDynamicArrayreverse(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)return*this;auto[a,b]=split_node(root,l);auto[mid,c]=split_node(b,r-l);returnmake_version(merge(merge(a,reversed_node(mid)),c),rng_state);}PersistentDynamicArrayreverse()const{returnmake_version(reversed_node(root),rng_state);}PersistentDynamicArrayrotate(intl,intm,intr)const{assert(0<=l&&l<=m&&m<=r&&r<=size());if(l==m||m==r)return*this;auto[a,b]=split_node(root,l);auto[c,d]=split_node(b,m-l);auto[e,f]=split_node(d,r-m);returnmake_version(merge(merge(a,e),merge(c,f)),rng_state);}std::pair<PersistentDynamicArray,PersistentDynamicArray>split(intpos)const{assert(0<=pos&&pos<=size());auto[l,r]=split_node(root,pos);PersistentDynamicArrayleft(l,rng_state,pool);PersistentDynamicArrayright(r,rng_state,pool);pool->discard_unreferenced();return{std::move(left),std::move(right)};}PersistentDynamicArraysplit_off(intpos)const{assert(0<=pos&&pos<=size());returnmake_version(split_node(root,pos).second,rng_state);}std::vector<T>to_vector()const{std::vector<T>res;res.reserve(size());dump_dfs(root,res);returnres;}std::vector<T>to_vector(intl,intr)const{assert(0<=l&&l<=r&&r<=size());std::vector<T>res;res.reserve(r-l);dump_range_dfs(root,l,r,0,res);returnres;}};}// namespace ds}// namespace m1une#line 1 "ds/dynamic_array/persistent_dynamic_lazy_monoid_array.hpp"
#line 13 "ds/dynamic_array/persistent_dynamic_lazy_monoid_array.hpp"
#line 1 "acted_monoid/concept.hpp"
#line 5 "acted_monoid/concept.hpp"
namespacem1une{namespaceacted_monoid{// Concept defining the requirements for an Acted Monoid.template<typenameAM>conceptIsActedMonoid=requires(typenameAM::value_typea,typenameAM::value_typeb,typenameAM::operator_typef,typenameAM::operator_typeg){// 1. Value MonoidtypenameAM::value_type;{AM::id()}->std::same_as<typenameAM::value_type>;{AM::op(a,b)}->std::same_as<typenameAM::value_type>;// 2. Operator MonoidtypenameAM::operator_type;{AM::op_id()}->std::same_as<typenameAM::operator_type>;{AM::op_comp(f,g)}->std::same_as<typenameAM::operator_type>;// Composition order: f(g(x))// 3. Mapping: Operator x Value -> Value{AM::mapping(f,a)}->std::same_as<typenameAM::value_type>;};// Concept for acted monoids whose value monoid is a commutative group.// The value operation must obey commutativity and inverse laws.template<typenameAM>conceptIsCommutativeActedGroup=IsActedMonoid<AM>&&requires(typenameAM::value_typea){{AM::inv(a)}->std::same_as<typenameAM::value_type>;};}// namespace acted_monoid}// namespace m1une#line 16 "ds/dynamic_array/persistent_dynamic_lazy_monoid_array.hpp"
namespacem1une{namespaceds{template<m1une::acted_monoid::IsActedMonoidActedMonoid>structPersistentDynamicLazyMonoidArray{usingT=typenameActedMonoid::value_type;usingF=typenameActedMonoid::operator_type;private:structNode{Tval,prod,rprod;Flazy;intpriority;intcount;intl,r;boolrev;boolhas_lazy;Node(Tvalue,Tproduct,Treverse_product,Flazy_value,intnode_priority,intnode_count,intleft,intright,boolreversed,boollazy_flag):val(std::move(value)),prod(std::move(product)),rprod(std::move(reverse_product)),lazy(std::move(lazy_value)),priority(node_priority),count(node_count),l(left),r(right),rev(reversed),has_lazy(lazy_flag){}};structBuildNode{Tval;intpriority;intl,r;BuildNode(Tvalue,intnode_priority):val(std::move(value)),priority(node_priority),l(-1),r(-1){}};introot;std::uint32_trng_state;usingPool=detail::PersistentBinaryNodePool<Node>;std::shared_ptr<Pool>pool;intsubtree_size(intt)const{returnt==-1?0:(*pool)[t].count;}Tnode_prod(intt)const{returnt==-1?ActedMonoid::id():(*pool)[t].prod;}Tnode_rprod(intt)const{returnt==-1?ActedMonoid::id():(*pool)[t].rprod;}staticstd::uint32_tnext_state(std::uint32_tstate){state^=state<<13;state^=state>>17;state^=state<<5;returnstate==0?1:state;}staticintnext_priority(std::uint32_t&state){state=next_state(state);returnint(state);}template<typenameU>staticTmake_value(constU&value){ifconstexpr(requires(Ux){ActedMonoid::make(x);}){returnActedMonoid::make(value);}else{returnstatic_cast<T>(value);}}staticTmapping_at(constF&f,constT&value,longlongord){ifconstexpr(requires(Fg,Tx,longlongi){ActedMonoid::mapping(g,x,i);}){returnActedMonoid::mapping(f,value,ord);}else{returnActedMonoid::mapping(f,value);}}staticFshift_operator(constF&f,longlongord){ifconstexpr(requires(Fg,longlongi){ActedMonoid::op_shift(g,i);}){returnActedMonoid::op_shift(f,ord);}else{returnf;}}staticFreverse_operator(constF&f,longlongsize){ifconstexpr(requires(Fg,longlongn){ActedMonoid::op_reverse(g,n);}){returnActedMonoid::op_reverse(f,size);}else{returnf;}}Fcompose_for_child(constF&inherited,intt,longlongord)const{Fshifted=shift_operator(inherited,ord);constNode&node=(*pool)[t];if(!node.has_lazy)returnshifted;returnActedMonoid::op_comp(shifted,shift_operator(node.lazy,ord));}intmake_raw_node(Tval,Tprod,Trprod,Flazy,intpriority,intcount,boolrev,boolhas_lazy,intl,intr)const{returnpool->emplace(std::move(val),std::move(prod),std::move(rprod),std::move(lazy),priority,count,l,r,rev,has_lazy);}intmake_node(Tval,intpriority,boolrev,intl,intr)const{Tprod=ActedMonoid::op(ActedMonoid::op(node_prod(l),val),node_prod(r));Trprod=ActedMonoid::op(ActedMonoid::op(node_rprod(r),val),node_rprod(l));if(rev)std::swap(prod,rprod);intcount=1+subtree_size(l)+subtree_size(r);returnmake_raw_node(std::move(val),std::move(prod),std::move(rprod),ActedMonoid::op_id(),priority,count,rev,false,l,r);}intreversed_node(intt)const{if(t==-1)return-1;Nodenode=(*pool)[t];Flazy=node.has_lazy?reverse_operator(node.lazy,node.count):node.lazy;returnmake_raw_node(std::move(node.val),std::move(node.rprod),std::move(node.prod),std::move(lazy),node.priority,node.count,!node.rev,node.has_lazy,node.l,node.r);}voidall_apply_to_node(intt,constF&f)const{Node&node=(*pool)[t];intleft_count=node.rev?subtree_size(node.r):subtree_size(node.l);node.val=mapping_at(f,node.val,left_count);node.prod=mapping_at(f,node.prod,0);node.rprod=mapping_at(reverse_operator(f,node.count),node.rprod,0);node.lazy=ActedMonoid::op_comp(f,node.lazy);node.has_lazy=true;}intall_apply(intt,constF&f)const{if(t==-1)return-1;intresult=pool->clone(t);all_apply_to_node(result,f);returnresult;}intpush(intt)const{if(t==-1)return-1;constNode&stored=(*pool)[t];if(!stored.rev&&!stored.has_lazy)returnt;Nodenode=stored;intl=node.l;intr=node.r;if(node.rev){std::swap(l,r);l=reversed_node(l);r=reversed_node(r);}if(node.has_lazy){l=all_apply(l,node.lazy);r=all_apply(r,shift_operator(node.lazy,subtree_size(l)+1));}returnmake_node(std::move(node.val),node.priority,false,l,r);}intmerge(intl,intr)const{if(l==-1||r==-1)returnl==-1?r:l;if((*pool)[l].priority>(*pool)[r].priority){Nodenode=(*pool)[push(l)];intright=merge(node.r,r);returnmake_node(std::move(node.val),node.priority,false,node.l,right);}Nodenode=(*pool)[push(r)];intleft=merge(l,node.l);returnmake_node(std::move(node.val),node.priority,false,left,node.r);}std::pair<int,int>split_node(intt,intpos)const{if(t==-1)return{-1,-1};Nodenode=(*pool)[push(t)];intleft_count=subtree_size(node.l);if(pos<=left_count){auto[a,b]=split_node(node.l,pos);return{a,make_node(std::move(node.val),node.priority,false,b,node.r)};}auto[a,b]=split_node(node.r,pos-left_count-1);return{make_node(std::move(node.val),node.priority,false,node.l,a),b};}intset_node(intt,intpos,Tval)const{Nodenode=(*pool)[push(t)];intleft_count=subtree_size(node.l);if(pos<left_count){intl=set_node(node.l,pos,std::move(val));returnmake_node(std::move(node.val),node.priority,false,l,node.r);}if(pos==left_count){returnmake_node(std::move(val),node.priority,false,node.l,node.r);}intr=set_node(node.r,pos-left_count-1,std::move(val));returnmake_node(std::move(node.val),node.priority,false,node.l,r);}voidreverse_node_inplace(intt)const{Node&node=(*pool)[t];std::swap(node.prod,node.rprod);if(node.has_lazy)node.lazy=reverse_operator(node.lazy,node.count);node.rev=!node.rev;}intreverse_node_cow(intt)const{if(t==-1)return-1;t=pool->clone_if_shared(t);reverse_node_inplace(t);returnt;}intall_apply_cow(intt,constF&f)const{if(t==-1)return-1;t=pool->clone_if_shared(t);all_apply_to_node(t,f);returnt;}voidpull(intt)const{Node&node=(*pool)[t];node.prod=ActedMonoid::op(ActedMonoid::op(node_prod(node.l),node.val),node_prod(node.r));node.rprod=ActedMonoid::op(ActedMonoid::op(node_rprod(node.r),node.val),node_rprod(node.l));}voidpush_inplace(intt)const{if(!(*pool)[t].rev&&!(*pool)[t].has_lazy)return;constboolreversed=(*pool)[t].rev;constboolhas_lazy=(*pool)[t].has_lazy;Flazy=(*pool)[t].lazy;intleft=(*pool)[t].l;intright=(*pool)[t].r;if(reversed){intnew_left=reverse_node_cow(right);intnew_right=reverse_node_cow(left);// Keep both children alive while the two owning edges are swapped.pool->retain(new_left);pool->retain(new_right);pool->replace((*pool)[t].l,new_left);pool->replace((*pool)[t].r,new_right);pool->release(new_left);pool->release(new_right);}if(has_lazy){left=all_apply_cow((*pool)[t].l,lazy);pool->replace((*pool)[t].l,left);right=all_apply_cow((*pool)[t].r,shift_operator(lazy,subtree_size(left)+1));pool->replace((*pool)[t].r,right);}Node&node=(*pool)[t];node.lazy=ActedMonoid::op_id();node.rev=false;node.has_lazy=false;pull(t);}intset_node_inplace(intt,intpos,Tval)const{t=pool->clone_if_shared(t);push_inplace(t);intleft_count=subtree_size((*pool)[t].l);if(pos<left_count){intchild=set_node_inplace((*pool)[t].l,pos,std::move(val));pool->replace((*pool)[t].l,child);}elseif(pos==left_count){(*pool)[t].val=std::move(val);}else{intchild=set_node_inplace((*pool)[t].r,pos-left_count-1,std::move(val));pool->replace((*pool)[t].r,child);}pull(t);returnt;}intapply_node_inplace(intt,intoffset,intquery_left,intquery_right,constF&f)const{if(t==-1||query_right<=offset||offset+subtree_size(t)<=query_left)returnt;t=pool->clone_if_shared(t);if(query_left<=offset&&offset+subtree_size(t)<=query_right){all_apply_to_node(t,shift_operator(f,offset-query_left));returnt;}push_inplace(t);intleft_count=subtree_size((*pool)[t].l);intchild=apply_node_inplace((*pool)[t].l,offset,query_left,query_right,f);pool->replace((*pool)[t].l,child);intposition=offset+left_count;if(query_left<=position&&position<query_right){(*pool)[t].val=mapping_at(shift_operator(f,position-query_left),(*pool)[t].val,0);}child=apply_node_inplace((*pool)[t].r,position+1,query_left,query_right,f);pool->replace((*pool)[t].r,child);pull(t);returnt;}Tget_value(intt,intpos,Finherited,boolreversed=false)const{while(t!=-1){constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);if(pos<left_count){inherited=compose_for_child(inherited,t,0);t=l;reversed=cur_reversed;}elseif(pos==left_count){returnmapping_at(inherited,node.val,left_count);}else{pos-=left_count+1;inherited=compose_for_child(inherited,t,left_count+1);t=r;reversed=cur_reversed;}}returnActedMonoid::id();}Tprod_dfs(intt,intql,intqr,intoffset,constF&inherited,boolreversed=false)const{if(t==-1||qr<=offset||offset+(*pool)[t].count<=ql)returnActedMonoid::id();constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;if(ql<=offset&&offset+node.count<=qr){returnmapping_at(inherited,reversed?node.rprod:node.prod,0);}intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);intnode_pos=offset+left_count;Tres=prod_dfs(l,ql,qr,offset,compose_for_child(inherited,t,0),cur_reversed);if(ql<=node_pos&&node_pos<qr)res=ActedMonoid::op(res,mapping_at(inherited,node.val,left_count));returnActedMonoid::op(res,prod_dfs(r,ql,qr,node_pos+1,compose_for_child(inherited,t,left_count+1),cur_reversed));}voiddump_dfs(intt,std::vector<T>&res,constF&inherited,boolreversed=false)const{if(t==-1)return;constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);dump_dfs(l,res,compose_for_child(inherited,t,0),cur_reversed);res.push_back(mapping_at(inherited,node.val,left_count));dump_dfs(r,res,compose_for_child(inherited,t,left_count+1),cur_reversed);}voiddump_range_dfs(intt,intql,intqr,intoffset,std::vector<T>&res,constF&inherited,boolreversed=false)const{if(t==-1||qr<=offset||offset+(*pool)[t].count<=ql)return;constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);intnode_pos=offset+left_count;dump_range_dfs(l,ql,qr,offset,res,compose_for_child(inherited,t,0),cur_reversed);if(ql<=node_pos&&node_pos<qr)res.push_back(mapping_at(inherited,node.val,left_count));dump_range_dfs(r,ql,qr,node_pos+1,res,compose_for_child(inherited,t,left_count+1),cur_reversed);}intbuild_from_nodes(std::vector<BuildNode>&nodes,intt)const{if(t==-1)return-1;intl=build_from_nodes(nodes,nodes[t].l);intr=build_from_nodes(nodes,nodes[t].r);returnmake_node(std::move(nodes[t].val),nodes[t].priority,false,l,r);}intbuild_cartesian(std::vector<BuildNode>&nodes)const{if(nodes.empty())return-1;std::vector<int>stack;stack.reserve(nodes.size());for(inti=0;i<int(nodes.size());i++){intleft_child=-1;while(!stack.empty()&&nodes[stack.back()].priority<nodes[i].priority){left_child=stack.back();stack.pop_back();}nodes[i].l=left_child;if(!stack.empty())nodes[stack.back()].r=i;stack.push_back(i);}returnbuild_from_nodes(nodes,stack.front());}intbuild_from_vector(conststd::vector<T>&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(constT&x:v)nodes.emplace_back(x,next_priority(state));returnbuild_cartesian(nodes);}intbuild_from_vector(std::vector<T>&&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(T&x:v)nodes.emplace_back(std::move(x),next_priority(state));returnbuild_cartesian(nodes);}template<typenameU>intbuild_from_values(conststd::vector<U>&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(constU&x:v)nodes.emplace_back(make_value(x),next_priority(state));returnbuild_cartesian(nodes);}intimport_node(constPersistentDynamicLazyMonoidArray&other,intt)const{if(t==-1)return-1;if(pool==other.pool)returnt;constNode&node=(*other.pool)[t];intl=import_node(other,node.l);intr=import_node(other,node.r);returnmake_raw_node(node.val,node.prod,node.rprod,node.lazy,node.priority,node.count,node.rev,node.has_lazy,l,r);}explicitPersistentDynamicLazyMonoidArray(intnode,std::uint32_tstate,std::shared_ptr<Pool>node_pool):root(node),rng_state(state),pool(std::move(node_pool)){pool->retain(root);}PersistentDynamicLazyMonoidArraymake_version(intnode,std::uint32_tstate)const{PersistentDynamicLazyMonoidArrayresult(node,state,pool);pool->discard_unreferenced();returnresult;}public:PersistentDynamicLazyMonoidArray():root(-1),rng_state(std::uint32_t(std::chrono::steady_clock::now().time_since_epoch().count())),pool(std::make_shared<Pool>()){if(rng_state==0)rng_state=1;}explicitPersistentDynamicLazyMonoidArray(intn):PersistentDynamicLazyMonoidArray(n,ActedMonoid::id()){}PersistentDynamicLazyMonoidArray(intn,constT&value):PersistentDynamicLazyMonoidArray(){assert(0<=n);pool->reserve(n);std::vector<T>v(n,value);root=build_from_vector(std::move(v),rng_state);pool->retain(root);pool->discard_unreferenced();}explicitPersistentDynamicLazyMonoidArray(conststd::vector<T>&v):PersistentDynamicLazyMonoidArray(){pool->reserve(v.size());root=build_from_vector(v,rng_state);pool->retain(root);pool->discard_unreferenced();}explicitPersistentDynamicLazyMonoidArray(std::vector<T>&&v):PersistentDynamicLazyMonoidArray(){pool->reserve(v.size());root=build_from_vector(std::move(v),rng_state);pool->retain(root);pool->discard_unreferenced();}template<typenameU>requires(!std::same_as<U,T>)&&(requires(Ux){ActedMonoid::make(x);}||std::convertible_to<U,T>)explicitPersistentDynamicLazyMonoidArray(conststd::vector<U>&v):PersistentDynamicLazyMonoidArray(){pool->reserve(v.size());root=build_from_values(v,rng_state);pool->retain(root);pool->discard_unreferenced();}PersistentDynamicLazyMonoidArray(std::initializer_list<T>init):PersistentDynamicLazyMonoidArray(std::vector<T>(init)){}PersistentDynamicLazyMonoidArray(constPersistentDynamicLazyMonoidArray&other):root(other.root),rng_state(other.rng_state),pool(other.pool){if(pool)pool->retain(root);}PersistentDynamicLazyMonoidArray(PersistentDynamicLazyMonoidArray&&other)noexcept:root(other.root),rng_state(other.rng_state),pool(std::move(other.pool)){other.root=-1;}PersistentDynamicLazyMonoidArray&operator=(constPersistentDynamicLazyMonoidArray&other){if(this==&other)return*this;if(other.pool)other.pool->retain(other.root);if(pool)pool->release(root);root=other.root;rng_state=other.rng_state;pool=other.pool;return*this;}PersistentDynamicLazyMonoidArray&operator=(PersistentDynamicLazyMonoidArray&&other)noexcept{if(this==&other)return*this;if(pool)pool->release(root);root=other.root;rng_state=other.rng_state;pool=std::move(other.pool);other.root=-1;return*this;}~PersistentDynamicLazyMonoidArray(){if(pool)pool->release(root);}intsize()const{returnsubtree_size(root);}boolempty()const{returnsize()==0;}voidrelease(){if(pool)pool->release(root);root=-1;pool=std::make_shared<Pool>();}std::size_tnode_count()const{returnpool?pool->size():0;}PersistentDynamicLazyMonoidArrayclear()const{returnmake_version(-1,rng_state);}PersistentDynamicLazyMonoidArrayinsert(intpos,Tvalue)const{assert(0<=pos&&pos<=size());std::uint32_tnext=next_state(rng_state);intnode=make_node(std::move(value),int(next),false,-1,-1);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,node),r),next);}PersistentDynamicLazyMonoidArrayinsert(intpos,conststd::vector<T>&v)const{assert(0<=pos&&pos<=size());if(v.empty())return*this;std::uint32_tnext=rng_state;intmid=build_from_vector(v,next);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),next);}PersistentDynamicLazyMonoidArrayinsert(intpos,std::vector<T>&&v)const{assert(0<=pos&&pos<=size());if(v.empty())return*this;std::uint32_tnext=rng_state;intmid=build_from_vector(std::move(v),next);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),next);}PersistentDynamicLazyMonoidArrayinsert(intpos,std::initializer_list<T>init)const{returninsert(pos,std::vector<T>(init));}PersistentDynamicLazyMonoidArrayinsert(intpos,constPersistentDynamicLazyMonoidArray&other)const{assert(0<=pos&&pos<=size());if(other.empty())return*this;intmid=import_node(other,other.root);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),rng_state);}PersistentDynamicLazyMonoidArraypush_back(Tvalue)const{returninsert(size(),std::move(value));}PersistentDynamicLazyMonoidArraypush_front(Tvalue)const{returninsert(0,std::move(value));}PersistentDynamicLazyMonoidArrayappend(conststd::vector<T>&v)const{returninsert(size(),v);}PersistentDynamicLazyMonoidArrayappend(std::vector<T>&&v)const{returninsert(size(),std::move(v));}PersistentDynamicLazyMonoidArrayappend(constPersistentDynamicLazyMonoidArray&other)const{returninsert(size(),other);}PersistentDynamicLazyMonoidArrayerase(intpos)const{assert(0<=pos&&pos<size());auto[a,b]=split_node(root,pos);auto[mid,c]=split_node(b,1);(void)mid;returnmake_version(merge(a,c),rng_state);}PersistentDynamicLazyMonoidArrayerase(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)return*this;auto[a,b]=split_node(root,l);auto[mid,c]=split_node(b,r-l);(void)mid;returnmake_version(merge(a,c),rng_state);}PersistentDynamicLazyMonoidArraypop_back()const{assert(!empty());returnerase(size()-1);}PersistentDynamicLazyMonoidArraypop_front()const{assert(!empty());returnerase(0);}Tget(intpos)const{assert(0<=pos&&pos<size());returnget_value(root,pos,ActedMonoid::op_id());}Toperator[](intpos)const{returnget(pos);}Tfront()const{assert(!empty());returnget(0);}Tback()const{assert(!empty());returnget(size()-1);}PersistentDynamicLazyMonoidArrayset(intpos,Tvalue)const{assert(0<=pos&&pos<size());returnmake_version(set_node(root,pos,std::move(value)),rng_state);}voidset_inplace(intpos,Tvalue){assert(0<=pos&&pos<size());intnext_root=set_node_inplace(root,pos,std::move(value));pool->replace(root,next_root);pool->discard_unreferenced();}PersistentDynamicLazyMonoidArrayreverse(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)return*this;auto[a,b]=split_node(root,l);auto[mid,c]=split_node(b,r-l);returnmake_version(merge(merge(a,reversed_node(mid)),c),rng_state);}PersistentDynamicLazyMonoidArrayreverse()const{returnmake_version(reversed_node(root),rng_state);}PersistentDynamicLazyMonoidArrayrotate(intl,intm,intr)const{assert(0<=l&&l<=m&&m<=r&&r<=size());if(l==m||m==r)return*this;auto[a,b]=split_node(root,l);auto[c,d]=split_node(b,m-l);auto[e,f]=split_node(d,r-m);returnmake_version(merge(merge(a,e),merge(c,f)),rng_state);}PersistentDynamicLazyMonoidArrayapply(intpos,constF&f)const{assert(0<=pos&&pos<size());returnapply(pos,pos+1,f);}PersistentDynamicLazyMonoidArrayapply(intl,intr,constF&f)const{assert(0<=l&&l<=r&&r<=size());if(l==r)return*this;auto[a,b]=split_node(root,l);auto[mid,c]=split_node(b,r-l);returnmake_version(merge(merge(a,all_apply(mid,f)),c),rng_state);}voidapply_inplace(intpos,constF&f){assert(0<=pos&&pos<size());apply_inplace(pos,pos+1,f);}voidapply_inplace(intl,intr,constF&f){assert(0<=l&&l<=r&&r<=size());if(l==r)return;intnext_root=apply_node_inplace(root,0,l,r,f);pool->replace(root,next_root);pool->discard_unreferenced();}Tprod(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)returnActedMonoid::id();returnprod_dfs(root,l,r,0,ActedMonoid::op_id());}Tall_prod()const{returnroot==-1?ActedMonoid::id():(*pool)[root].prod;}std::pair<PersistentDynamicLazyMonoidArray,PersistentDynamicLazyMonoidArray>split(intpos)const{assert(0<=pos&&pos<=size());auto[l,r]=split_node(root,pos);PersistentDynamicLazyMonoidArrayleft(l,rng_state,pool);PersistentDynamicLazyMonoidArrayright(r,rng_state,pool);pool->discard_unreferenced();return{std::move(left),std::move(right)};}PersistentDynamicLazyMonoidArraysplit_off(intpos)const{assert(0<=pos&&pos<=size());returnmake_version(split_node(root,pos).second,rng_state);}std::vector<T>to_vector()const{std::vector<T>res;res.reserve(size());dump_dfs(root,res,ActedMonoid::op_id());returnres;}std::vector<T>to_vector(intl,intr)const{assert(0<=l&&l<=r&&r<=size());std::vector<T>res;res.reserve(r-l);dump_range_dfs(root,l,r,0,res,ActedMonoid::op_id());returnres;}};}// namespace ds}// namespace m1une#line 1 "ds/dynamic_array/persistent_dynamic_monoid_array.hpp"
#line 13 "ds/dynamic_array/persistent_dynamic_monoid_array.hpp"
#line 16 "ds/dynamic_array/persistent_dynamic_monoid_array.hpp"
namespacem1une{namespaceds{template<m1une::monoid::IsMonoidMonoid>structPersistentDynamicMonoidArray{usingT=typenameMonoid::value_type;private:structNode{Tval,prod,rprod;intpriority;intcount;intl,r;boolrev;Node(Tvalue,Tproduct,Treverse_product,intnode_priority,intnode_count,intleft,intright,boolreversed):val(std::move(value)),prod(std::move(product)),rprod(std::move(reverse_product)),priority(node_priority),count(node_count),l(left),r(right),rev(reversed){}};structBuildNode{Tval;intpriority;intl,r;BuildNode(Tvalue,intnode_priority):val(std::move(value)),priority(node_priority),l(-1),r(-1){}};introot;std::uint32_trng_state;usingPool=detail::PersistentBinaryNodePool<Node>;std::shared_ptr<Pool>pool;intsubtree_size(intt)const{returnt==-1?0:(*pool)[t].count;}Tnode_prod(intt)const{returnt==-1?Monoid::id():(*pool)[t].prod;}Tnode_rprod(intt)const{returnt==-1?Monoid::id():(*pool)[t].rprod;}staticstd::uint32_tnext_state(std::uint32_tstate){state^=state<<13;state^=state>>17;state^=state<<5;returnstate==0?1:state;}staticintnext_priority(std::uint32_t&state){state=next_state(state);returnint(state);}template<typenameU>staticTmake_value(constU&value){ifconstexpr(requires(Ux){Monoid::make(x);}){returnMonoid::make(value);}else{returnstatic_cast<T>(value);}}intmake_node(Tval,intpriority,boolrev,intl,intr)const{Tprod=Monoid::op(Monoid::op(node_prod(l),val),node_prod(r));Trprod=Monoid::op(Monoid::op(node_rprod(r),val),node_rprod(l));if(rev)std::swap(prod,rprod);intcount=1+subtree_size(l)+subtree_size(r);returnpool->emplace(std::move(val),std::move(prod),std::move(rprod),priority,count,l,r,rev);}intreversed_node(intt)const{if(t==-1)return-1;Nodenode=(*pool)[t];returnmake_node(std::move(node.val),node.priority,!node.rev,node.l,node.r);}intpush(intt)const{if(t==-1||!(*pool)[t].rev)returnt;Nodenode=(*pool)[t];intl=reversed_node(node.r);intr=reversed_node(node.l);returnmake_node(std::move(node.val),node.priority,false,l,r);}intmerge(intl,intr)const{if(l==-1||r==-1)returnl==-1?r:l;if((*pool)[l].priority>(*pool)[r].priority){Nodenode=(*pool)[push(l)];intright=merge(node.r,r);returnmake_node(std::move(node.val),node.priority,false,node.l,right);}Nodenode=(*pool)[push(r)];intleft=merge(l,node.l);returnmake_node(std::move(node.val),node.priority,false,left,node.r);}std::pair<int,int>split_node(intt,intpos)const{if(t==-1)return{-1,-1};Nodenode=(*pool)[push(t)];intleft_count=subtree_size(node.l);if(pos<=left_count){auto[a,b]=split_node(node.l,pos);return{a,make_node(std::move(node.val),node.priority,false,b,node.r)};}auto[a,b]=split_node(node.r,pos-left_count-1);return{make_node(std::move(node.val),node.priority,false,node.l,a),b};}intset_node(intt,intpos,Tval)const{Nodenode=(*pool)[push(t)];intleft_count=subtree_size(node.l);if(pos<left_count){intl=set_node(node.l,pos,std::move(val));returnmake_node(std::move(node.val),node.priority,false,l,node.r);}if(pos==left_count){returnmake_node(std::move(val),node.priority,false,node.l,node.r);}intr=set_node(node.r,pos-left_count-1,std::move(val));returnmake_node(std::move(node.val),node.priority,false,node.l,r);}voidpull(intt)const{Node&node=(*pool)[t];node.prod=Monoid::op(Monoid::op(node_prod(node.l),node.val),node_prod(node.r));node.rprod=Monoid::op(Monoid::op(node_rprod(node.r),node.val),node_rprod(node.l));if(node.rev)std::swap(node.prod,node.rprod);}intset_node_inplace(intt,intpos,Tval,boolinherited_reversed=false)const{t=pool->clone_if_shared(t);constboolreversed=inherited_reversed^(*pool)[t].rev;constintlogical_left=reversed?(*pool)[t].r:(*pool)[t].l;constintleft_count=subtree_size(logical_left);if(pos<left_count){intchild=set_node_inplace(logical_left,pos,std::move(val),reversed);if(reversed){pool->replace((*pool)[t].r,child);}else{pool->replace((*pool)[t].l,child);}}elseif(pos==left_count){(*pool)[t].val=std::move(val);}else{constintlogical_right=reversed?(*pool)[t].l:(*pool)[t].r;intchild=set_node_inplace(logical_right,pos-left_count-1,std::move(val),reversed);if(reversed){pool->replace((*pool)[t].l,child);}else{pool->replace((*pool)[t].r,child);}}pull(t);returnt;}intfind_node(intt,intpos)const{boolreversed=false;while(t!=-1){constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);if(pos<left_count){t=l;reversed=cur_reversed;}elseif(pos==left_count){returnt;}else{pos-=left_count+1;t=r;reversed=cur_reversed;}}return-1;}Tprod_dfs(intt,intql,intqr,intoffset,boolreversed=false)const{if(t==-1||qr<=offset||offset+(*pool)[t].count<=ql)returnMonoid::id();constNode&node=(*pool)[t];if(ql<=offset&&offset+node.count<=qr)returnreversed?node.rprod:node.prod;boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);intnode_pos=offset+left_count;Tres=prod_dfs(l,ql,qr,offset,cur_reversed);if(ql<=node_pos&&node_pos<qr)res=Monoid::op(res,node.val);returnMonoid::op(res,prod_dfs(r,ql,qr,node_pos+1,cur_reversed));}voiddump_dfs(intt,std::vector<T>&res,boolreversed=false)const{if(t==-1)return;constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;dump_dfs(l,res,cur_reversed);res.push_back(node.val);dump_dfs(r,res,cur_reversed);}voiddump_range_dfs(intt,intql,intqr,intoffset,std::vector<T>&res,boolreversed=false)const{if(t==-1||qr<=offset||offset+(*pool)[t].count<=ql)return;constNode&node=(*pool)[t];boolcur_reversed=reversed^node.rev;intl=cur_reversed?node.r:node.l;intr=cur_reversed?node.l:node.r;intleft_count=subtree_size(l);intnode_pos=offset+left_count;dump_range_dfs(l,ql,qr,offset,res,cur_reversed);if(ql<=node_pos&&node_pos<qr)res.push_back(node.val);dump_range_dfs(r,ql,qr,node_pos+1,res,cur_reversed);}intbuild_from_nodes(std::vector<BuildNode>&nodes,intt)const{if(t==-1)return-1;intl=build_from_nodes(nodes,nodes[t].l);intr=build_from_nodes(nodes,nodes[t].r);returnmake_node(std::move(nodes[t].val),nodes[t].priority,false,l,r);}intbuild_cartesian(std::vector<BuildNode>&nodes)const{if(nodes.empty())return-1;std::vector<int>stack;stack.reserve(nodes.size());for(inti=0;i<int(nodes.size());i++){intleft_child=-1;while(!stack.empty()&&nodes[stack.back()].priority<nodes[i].priority){left_child=stack.back();stack.pop_back();}nodes[i].l=left_child;if(!stack.empty())nodes[stack.back()].r=i;stack.push_back(i);}returnbuild_from_nodes(nodes,stack.front());}intbuild_from_vector(conststd::vector<T>&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(constT&x:v)nodes.emplace_back(x,next_priority(state));returnbuild_cartesian(nodes);}intbuild_from_vector(std::vector<T>&&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(T&x:v)nodes.emplace_back(std::move(x),next_priority(state));returnbuild_cartesian(nodes);}template<typenameU>intbuild_from_values(conststd::vector<U>&v,std::uint32_t&state)const{std::vector<BuildNode>nodes;nodes.reserve(v.size());for(constU&x:v)nodes.emplace_back(make_value(x),next_priority(state));returnbuild_cartesian(nodes);}intimport_node(constPersistentDynamicMonoidArray&other,intt)const{if(t==-1)return-1;if(pool==other.pool)returnt;constNode&node=(*other.pool)[t];intl=import_node(other,node.l);intr=import_node(other,node.r);returnmake_node(node.val,node.priority,node.rev,l,r);}explicitPersistentDynamicMonoidArray(intnode,std::uint32_tstate,std::shared_ptr<Pool>node_pool):root(node),rng_state(state),pool(std::move(node_pool)){pool->retain(root);}PersistentDynamicMonoidArraymake_version(intnode,std::uint32_tstate)const{PersistentDynamicMonoidArrayresult(node,state,pool);pool->discard_unreferenced();returnresult;}public:PersistentDynamicMonoidArray():root(-1),rng_state(std::uint32_t(std::chrono::steady_clock::now().time_since_epoch().count())),pool(std::make_shared<Pool>()){if(rng_state==0)rng_state=1;}explicitPersistentDynamicMonoidArray(intn):PersistentDynamicMonoidArray(n,Monoid::id()){}PersistentDynamicMonoidArray(intn,constT&value):PersistentDynamicMonoidArray(){assert(0<=n);pool->reserve(n);std::vector<T>v(n,value);root=build_from_vector(std::move(v),rng_state);pool->retain(root);pool->discard_unreferenced();}explicitPersistentDynamicMonoidArray(conststd::vector<T>&v):PersistentDynamicMonoidArray(){pool->reserve(v.size());root=build_from_vector(v,rng_state);pool->retain(root);pool->discard_unreferenced();}explicitPersistentDynamicMonoidArray(std::vector<T>&&v):PersistentDynamicMonoidArray(){pool->reserve(v.size());root=build_from_vector(std::move(v),rng_state);pool->retain(root);pool->discard_unreferenced();}template<typenameU>requires(!std::same_as<U,T>)&&(requires(Ux){Monoid::make(x);}||std::convertible_to<U,T>)explicitPersistentDynamicMonoidArray(conststd::vector<U>&v):PersistentDynamicMonoidArray(){pool->reserve(v.size());root=build_from_values(v,rng_state);pool->retain(root);pool->discard_unreferenced();}PersistentDynamicMonoidArray(std::initializer_list<T>init):PersistentDynamicMonoidArray(std::vector<T>(init)){}PersistentDynamicMonoidArray(constPersistentDynamicMonoidArray&other):root(other.root),rng_state(other.rng_state),pool(other.pool){if(pool)pool->retain(root);}PersistentDynamicMonoidArray(PersistentDynamicMonoidArray&&other)noexcept:root(other.root),rng_state(other.rng_state),pool(std::move(other.pool)){other.root=-1;}PersistentDynamicMonoidArray&operator=(constPersistentDynamicMonoidArray&other){if(this==&other)return*this;if(other.pool)other.pool->retain(other.root);if(pool)pool->release(root);root=other.root;rng_state=other.rng_state;pool=other.pool;return*this;}PersistentDynamicMonoidArray&operator=(PersistentDynamicMonoidArray&&other)noexcept{if(this==&other)return*this;if(pool)pool->release(root);root=other.root;rng_state=other.rng_state;pool=std::move(other.pool);other.root=-1;return*this;}~PersistentDynamicMonoidArray(){if(pool)pool->release(root);}intsize()const{returnsubtree_size(root);}boolempty()const{returnsize()==0;}voidrelease(){if(pool)pool->release(root);root=-1;pool=std::make_shared<Pool>();}std::size_tnode_count()const{returnpool?pool->size():0;}PersistentDynamicMonoidArrayclear()const{returnmake_version(-1,rng_state);}PersistentDynamicMonoidArrayinsert(intpos,Tvalue)const{assert(0<=pos&&pos<=size());std::uint32_tnext=next_state(rng_state);intnode=make_node(std::move(value),int(next),false,-1,-1);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,node),r),next);}PersistentDynamicMonoidArrayinsert(intpos,conststd::vector<T>&v)const{assert(0<=pos&&pos<=size());if(v.empty())return*this;std::uint32_tnext=rng_state;intmid=build_from_vector(v,next);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),next);}PersistentDynamicMonoidArrayinsert(intpos,std::vector<T>&&v)const{assert(0<=pos&&pos<=size());if(v.empty())return*this;std::uint32_tnext=rng_state;intmid=build_from_vector(std::move(v),next);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),next);}PersistentDynamicMonoidArrayinsert(intpos,std::initializer_list<T>init)const{returninsert(pos,std::vector<T>(init));}PersistentDynamicMonoidArrayinsert(intpos,constPersistentDynamicMonoidArray&other)const{assert(0<=pos&&pos<=size());if(other.empty())return*this;intmid=import_node(other,other.root);auto[l,r]=split_node(root,pos);returnmake_version(merge(merge(l,mid),r),rng_state);}PersistentDynamicMonoidArraypush_back(Tvalue)const{returninsert(size(),std::move(value));}PersistentDynamicMonoidArraypush_front(Tvalue)const{returninsert(0,std::move(value));}PersistentDynamicMonoidArrayappend(conststd::vector<T>&v)const{returninsert(size(),v);}PersistentDynamicMonoidArrayappend(std::vector<T>&&v)const{returninsert(size(),std::move(v));}PersistentDynamicMonoidArrayappend(constPersistentDynamicMonoidArray&other)const{returninsert(size(),other);}PersistentDynamicMonoidArrayerase(intpos)const{assert(0<=pos&&pos<size());auto[a,b]=split_node(root,pos);auto[mid,c]=split_node(b,1);(void)mid;returnmake_version(merge(a,c),rng_state);}PersistentDynamicMonoidArrayerase(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)return*this;auto[a,b]=split_node(root,l);auto[mid,c]=split_node(b,r-l);(void)mid;returnmake_version(merge(a,c),rng_state);}PersistentDynamicMonoidArraypop_back()const{assert(!empty());returnerase(size()-1);}PersistentDynamicMonoidArraypop_front()const{assert(!empty());returnerase(0);}Tget(intpos)const{assert(0<=pos&&pos<size());return(*pool)[find_node(root,pos)].val;}Toperator[](intpos)const{returnget(pos);}Tfront()const{assert(!empty());returnget(0);}Tback()const{assert(!empty());returnget(size()-1);}PersistentDynamicMonoidArrayset(intpos,Tvalue)const{assert(0<=pos&&pos<size());returnmake_version(set_node(root,pos,std::move(value)),rng_state);}voidset_inplace(intpos,Tvalue){assert(0<=pos&&pos<size());intnext_root=set_node_inplace(root,pos,std::move(value));pool->replace(root,next_root);pool->discard_unreferenced();}PersistentDynamicMonoidArrayreverse(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)return*this;auto[a,b]=split_node(root,l);auto[mid,c]=split_node(b,r-l);returnmake_version(merge(merge(a,reversed_node(mid)),c),rng_state);}PersistentDynamicMonoidArrayreverse()const{returnmake_version(reversed_node(root),rng_state);}PersistentDynamicMonoidArrayrotate(intl,intm,intr)const{assert(0<=l&&l<=m&&m<=r&&r<=size());if(l==m||m==r)return*this;auto[a,b]=split_node(root,l);auto[c,d]=split_node(b,m-l);auto[e,f]=split_node(d,r-m);returnmake_version(merge(merge(a,e),merge(c,f)),rng_state);}Tprod(intl,intr)const{assert(0<=l&&l<=r&&r<=size());if(l==r)returnMonoid::id();returnprod_dfs(root,l,r,0);}Tall_prod()const{returnroot==-1?Monoid::id():(*pool)[root].prod;}std::pair<PersistentDynamicMonoidArray,PersistentDynamicMonoidArray>split(intpos)const{assert(0<=pos&&pos<=size());auto[l,r]=split_node(root,pos);PersistentDynamicMonoidArrayleft(l,rng_state,pool);PersistentDynamicMonoidArrayright(r,rng_state,pool);pool->discard_unreferenced();return{std::move(left),std::move(right)};}PersistentDynamicMonoidArraysplit_off(intpos)const{assert(0<=pos&&pos<=size());returnmake_version(split_node(root,pos).second,rng_state);}std::vector<T>to_vector()const{std::vector<T>res;res.reserve(size());dump_dfs(root,res);returnres;}std::vector<T>to_vector(intl,intr)const{assert(0<=l&&l<=r&&r<=size());std::vector<T>res;res.reserve(r-l);dump_range_dfs(root,l,r,0,res);returnres;}};}// namespace ds}// namespace m1une#line 1 "ds/segtree/persistent_dual_segtree.hpp"
#line 9 "ds/segtree/persistent_dual_segtree.hpp"
#line 1 "ds/segtree/persistent_node_pool.hpp"
#line 9 "ds/segtree/persistent_node_pool.hpp"
namespacem1une{namespaceds{namespacedetail{// Node must have integer `left`, `right`, and `references` members.template<classNode>structPersistentNodePool{std::vector<Node>nodes;intfirst_free=0;std::size_tlive_nodes=0;private:voidrelease_zero(intnode){intleft=nodes[node].left;intright=nodes[node].right;nodes[node]=Node();nodes[node].left=first_free;first_free=node;--live_nodes;if(left&&--nodes[left].references==0)release_zero(left);if(right&&--nodes[right].references==0)release_zero(right);}public:PersistentNodePool(){nodes.emplace_back();}voidreserve(std::size_tcapacity){nodes.reserve(capacity+1);}Node&operator[](intnode){returnnodes[node];}constNode&operator[](intnode)const{returnnodes[node];}voidretain(intnode){if(node)++nodes[node].references;}voidrelease(intnode){if(!node)return;assert(nodes[node].references>0);if(--nodes[node].references==0)release_zero(node);}template<class...Args>intemplace(Args&&...args){intresult;if(!first_free){assert(nodes.size()<std::size_t(std::numeric_limits<int>::max()));nodes.emplace_back(std::forward<Args>(args)...);result=int(nodes.size())-1;}else{result=first_free;first_free=nodes[result].left;nodes[result]=Node(std::forward<Args>(args)...);}Node&node=nodes[result];node.references=0;retain(node.left);retain(node.right);++live_nodes;returnresult;}intclone(intnode){assert(node);Nodecopy=nodes[node];returnemplace(std::move(copy));}boolunique(intnode)const{return!node||nodes[node].references==1;}// Returns node itself when it has one owner, otherwise an unowned clone.// The caller must attach a returned clone with replace() before it can be// released or exposed as a root.intclone_if_shared(intnode){if(unique(node))returnnode;returnclone(node);}voidreplace(int&edge,intnode){if(edge==node)return;retain(node);intold=edge;edge=node;release(old);}std::size_tsize()const{returnlive_nodes;}};}// namespace detail}// namespace ds}// namespace m1une#line 12 "ds/segtree/persistent_dual_segtree.hpp"
namespacem1une{namespaceds{template<m1une::monoid::IsMonoidMonoid>structPersistentDualSegtree{usingT=typenameMonoid::value_type;private:structNode{Tval;intleft,right;intreferences;boolhas_lazy;Node():val(Monoid::id()),left(0),right(0),references(0),has_lazy(false){}explicitNode(Tvalue):val(std::move(value)),left(0),right(0),references(0),has_lazy(false){}Node(intleft_child,intright_child):val(Monoid::id()),left(left_child),right(right_child),references(0),has_lazy(false){}};usingPool=detail::PersistentNodePool<Node>;int_n;int_root;std::shared_ptr<Pool>_pool;explicitPersistentDualSegtree(intn,introot,std::shared_ptr<Pool>pool):_n(n),_root(root),_pool(std::move(pool)){_pool->retain(_root);}intnew_node(constNode&node)const{return_pool->emplace(node);}intnew_node(Node&&node)const{return_pool->emplace(std::move(node));}intclone_node(intt)const{return_pool->clone(t);}template<typenameU>staticTmake_value(constU&value,intindex){ifconstexpr(requires(Ux){Monoid::make(x);}){returnMonoid::make(value);}elseifconstexpr(requires(Ux,inti){Monoid::make(x,i);}){returnMonoid::make(value,index);}else{returnstatic_cast<T>(value);}}Tcompose_for_child(constT&inherited,constNode&node)const{if(!node.has_lazy)returninherited;returnMonoid::op(inherited,node.val);}intbuild(intl,intr,conststd::vector<T>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(v[l]));intm=(l+r)>>1;returnnew_node(Node(build(l,m,v),build(m,r,v)));}intbuild(intl,intr,std::vector<T>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(std::move(v[l])));intm=(l+r)>>1;returnnew_node(Node(build(l,m,v),build(m,r,v)));}template<typenameU>intbuild_from_values(intl,intr,conststd::vector<U>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(make_value(v[l],l)));intm=(l+r)>>1;returnnew_node(Node(build_from_values(l,m,v),build_from_values(m,r,v)));}voidall_apply_to_node(intt,constT&x,intl,intr)const{Node&node=(*_pool)[t];if(r-l==1){node.val=Monoid::op(x,node.val);}else{node.val=node.has_lazy?Monoid::op(x,node.val):x;node.has_lazy=true;}}intall_apply_clone(intt,constT&x,intl,intr,boolcopy_on_write=false)const{intres=copy_on_write?_pool->clone_if_shared(t):clone_node(t);all_apply_to_node(res,x,l,r);returnres;}voidpush(intt,intl,intr,boolcopy_on_write=false)const{Nodenode=(*_pool)[t];if(!node.has_lazy||r-l==1)return;intm=(l+r)>>1;intleft=all_apply_clone(node.left,node.val,l,m,copy_on_write);intright=all_apply_clone(node.right,node.val,m,r,copy_on_write);Node&target=(*_pool)[t];_pool->replace(target.left,left);_pool->replace(target.right,right);target.val=Monoid::id();target.has_lazy=false;}intset_node(intt,intl,intr,intp,Tvalue,boolcopy_on_write=false)const{t=copy_on_write?_pool->clone_if_shared(t):clone_node(t);if(r-l==1){Node&node=(*_pool)[t];node.val=std::move(value);node.has_lazy=false;returnt;}push(t,l,r,copy_on_write);intm=(l+r)>>1;if(p<m){intchild=set_node((*_pool)[t].left,l,m,p,std::move(value),copy_on_write);_pool->replace((*_pool)[t].left,child);}else{intchild=set_node((*_pool)[t].right,m,r,p,std::move(value),copy_on_write);_pool->replace((*_pool)[t].right,child);}returnt;}intapply_node(intt,intl,intr,intql,intqr,constT&x,boolcopy_on_write=false)const{if(qr<=l||r<=ql)returnt;t=copy_on_write?_pool->clone_if_shared(t):clone_node(t);if(ql<=l&&r<=qr){all_apply_to_node(t,x,l,r);returnt;}push(t,l,r,copy_on_write);intm=(l+r)>>1;intleft=apply_node((*_pool)[t].left,l,m,ql,qr,x,copy_on_write);intright=apply_node((*_pool)[t].right,m,r,ql,qr,x,copy_on_write);_pool->replace((*_pool)[t].left,left);_pool->replace((*_pool)[t].right,right);returnt;}Tget_node(intt,intl,intr,intp,constT&inherited)const{constNode&node=(*_pool)[t];if(r-l==1)returnMonoid::op(inherited,node.val);intm=(l+r)>>1;if(p<m)returnget_node(node.left,l,m,p,compose_for_child(inherited,node));returnget_node(node.right,m,r,p,compose_for_child(inherited,node));}voidcollect_node(intt,intl,intr,intql,intqr,constT&inherited,std::vector<T>&res)const{if(!t||qr<=l||r<=ql)return;constNode&node=(*_pool)[t];if(r-l==1){res.push_back(Monoid::op(inherited,node.val));return;}intm=(l+r)>>1;Tnext=compose_for_child(inherited,node);collect_node(node.left,l,m,ql,qr,next,res);collect_node(node.right,m,r,ql,qr,next,res);}public:PersistentDualSegtree():PersistentDualSegtree(0){}explicitPersistentDualSegtree(intn):_n(n),_root(0),_pool(std::make_shared<Pool>()){assert(0<=n);if(_n>0)_root=build(0,_n,std::vector<T>(_n,Monoid::id()));_pool->retain(_root);}explicitPersistentDualSegtree(conststd::vector<T>&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build(0,_n,v);_pool->retain(_root);}explicitPersistentDualSegtree(std::vector<T>&&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build(0,_n,v);_pool->retain(_root);}template<typenameU>requires(!std::same_as<U,T>)&&(requires(Ux){Monoid::make(x);}||requires(Ux,inti){Monoid::make(x,i);}||std::convertible_to<U,T>)explicitPersistentDualSegtree(conststd::vector<U>&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build_from_values(0,_n,v);_pool->retain(_root);}PersistentDualSegtree(constPersistentDualSegtree&other):_n(other._n),_root(other._root),_pool(other._pool){if(_pool)_pool->retain(_root);}PersistentDualSegtree(PersistentDualSegtree&&other)noexcept:_n(other._n),_root(other._root),_pool(std::move(other._pool)){other._n=0;other._root=0;}PersistentDualSegtree&operator=(constPersistentDualSegtree&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=other._pool;return*this;}PersistentDualSegtree&operator=(PersistentDualSegtree&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=std::move(other._pool);other._n=0;other._root=0;return*this;}~PersistentDualSegtree(){if(_pool)_pool->release(_root);}intsize()const{return_n;}boolempty()const{return_n==0;}voidrelease(){if(_pool)_pool->release(_root);_pool=std::make_shared<Pool>();_root=0;_n=0;}std::size_tnode_count()const{return_pool?_pool->size():0;}PersistentDualSegtreeset(intp,Tx)const{assert(0<=p&&p<_n);returnPersistentDualSegtree(_n,set_node(_root,0,_n,p,std::move(x)),_pool);}voidset_inplace(intp,Tx){assert(0<=p&&p<_n);introot=set_node(_root,0,_n,p,std::move(x),true);_pool->replace(_root,root);}Tget(intp)const{assert(0<=p&&p<_n);returnget_node(_root,0,_n,p,Monoid::id());}Toperator[](intp)const{returnget(p);}PersistentDualSegtreeapply(intp,constT&x)const{assert(0<=p&&p<_n);returnapply(p,p+1,x);}PersistentDualSegtreeapply(intl,intr,constT&x)const{assert(0<=l&&l<=r&&r<=_n);if(l==r)return*this;returnPersistentDualSegtree(_n,apply_node(_root,0,_n,l,r,x),_pool);}voidapply_inplace(intp,constT&x){assert(0<=p&&p<_n);apply_inplace(p,p+1,x);}voidapply_inplace(intl,intr,constT&x){assert(0<=l&&l<=r&&r<=_n);if(l==r)return;introot=apply_node(_root,0,_n,l,r,x,true);_pool->replace(_root,root);}std::vector<T>to_vector()const{returnto_vector(0,_n);}std::vector<T>to_vector(intl,intr)const{assert(0<=l&&l<=r&&r<=_n);std::vector<T>res;res.reserve(r-l);collect_node(_root,0,_n,l,r,Monoid::id(),res);returnres;}};}// namespace ds}// namespace m1une#line 1 "ds/segtree/persistent_dynamic_dual_segtree.hpp"
#line 9 "ds/segtree/persistent_dynamic_dual_segtree.hpp"
#include<numeric>
#include<type_traits>
#line 13 "ds/segtree/persistent_dynamic_dual_segtree.hpp"
#line 1 "ds/segtree/dynamic_segtree_common.hpp"
#line 11 "ds/segtree/dynamic_segtree_common.hpp"
namespacem1une{namespaceds{namespacedetail{template<std::integralIndex>usingdynamic_size_type=std::make_unsigned_t<Index>;template<std::integralIndex>constexprdynamic_size_type<Index>dynamic_distance(Indexleft,Indexright){returnstatic_cast<dynamic_size_type<Index>>(right)-static_cast<dynamic_size_type<Index>>(left);}template<classMonoid,classSize>typenameMonoid::value_typemonoid_repeat(typenameMonoid::value_typevalue,Sizecount){typenameMonoid::value_typeresult=Monoid::id();while(count!=0){if(count&1)result=Monoid::op(result,value);count>>=1;if(count!=0)value=Monoid::op(value,value);}returnresult;}template<classActedMonoid>typenameActedMonoid::value_typedynamic_mapping(consttypenameActedMonoid::operator_type&f,consttypenameActedMonoid::value_type&value){usingF=typenameActedMonoid::operator_type;usingT=typenameActedMonoid::value_type;ifconstexpr(requires(Fg,Tx,longlongord){ActedMonoid::mapping(g,x,ord);}){returnActedMonoid::mapping(f,value,0);}else{returnActedMonoid::mapping(f,value);}}template<classActedMonoid,classSize>typenameActedMonoid::operator_typedynamic_shift(consttypenameActedMonoid::operator_type&f,Sizeoffset){usingF=typenameActedMonoid::operator_type;ifconstexpr(requires(Fg,longlongord){ActedMonoid::op_shift(g,ord);}){assert(offset<=static_cast<Size>(std::numeric_limits<longlong>::max()));returnActedMonoid::op_shift(f,static_cast<longlong>(offset));}else{returnf;}}template<classMonoid,std::integralIndex>classUniformMonoidDomain{public:usingT=typenameMonoid::value_type;usingsize_type=dynamic_size_type<Index>;private:structLevel{size_typesmall_length;Tsmall_value;Tlarge_value;};Index_left;Index_right;T_initial_value;std::vector<Level>_levels;public:UniformMonoidDomain(Indexleft,Indexright,Tinitial_value):_left(left),_right(right),_initial_value(std::move(initial_value)){assert(left<=right);size_typen=size();constexprintdigits=std::numeric_limits<size_type>::digits;_levels.reserve(digits+1);for(intdepth=0;depth<=digits;depth++){size_typesmall=depth==digits?0:n>>depth;size_typelarge=small;if(depth!=0){boolhas_remainder;if(depth==digits){has_remainder=n!=0;}else{size_typemask=(size_type(1)<<depth)-1;has_remainder=(n&mask)!=0;}if(has_remainder)large++;}_levels.push_back(Level{small,monoid_repeat<Monoid>(_initial_value,small),monoid_repeat<Monoid>(_initial_value,large),});}}Indexleft_bound()const{return_left;}Indexright_bound()const{return_right;}size_typesize()const{returndynamic_distance(_left,_right);}boolempty()const{return_left==_right;}constT&initial_value()const{return_initial_value;}constT&default_product(intdepth,Indexleft,Indexright)const{assert(0<=depth&&depth<int(_levels.size()));constLevel&level=_levels[depth];size_typelength=dynamic_distance(left,right);if(length==level.small_length)returnlevel.small_value;assert(length==level.small_length+1);returnlevel.large_value;}};}// namespace detail}// namespace ds}// namespace m1une#line 17 "ds/segtree/persistent_dynamic_dual_segtree.hpp"
namespacem1une{namespaceds{// A persistent sparse dual segment tree over an integral half-open interval.template<m1une::monoid::IsMonoidMonoid,std::integralIndex=longlong>requires(!std::same_as<std::remove_cv_t<Index>,bool>)structPersistentDynamicDualSegtree{usingT=typenameMonoid::value_type;usingindex_type=Index;usingsize_type=detail::dynamic_size_type<Index>;private:structNode{Tval;intleft;intright;intreferences;boolhas_lazy;Node():val(Monoid::id()),left(0),right(0),references(0),has_lazy(false){}};structConfig{Indexleft;Indexright;Tinitial_value;Config(Indexleft_bound,Indexright_bound,Tvalue):left(left_bound),right(right_bound),initial_value(std::move(value)){assert(left<=right);}};std::shared_ptr<constConfig>_config;usingPool=detail::PersistentNodePool<Node>;std::shared_ptr<Pool>_pool;int_root;PersistentDynamicDualSegtree(std::shared_ptr<constConfig>config,std::shared_ptr<Pool>pool,introot):_config(std::move(config)),_pool(std::move(pool)),_root(root){_pool->retain(_root);}intnew_node()const{return_pool->emplace();}intclone_or_new(intt,boolcopy_on_write=false)const{if(!t)returnnew_node();returncopy_on_write?_pool->clone_if_shared(t):_pool->clone(t);}voidall_apply_to_node(intt,Indexleft,Indexright,constT&x)const{Node&node=(*_pool)[t];if(std::midpoint(left,right)==left){Tvalue=node.has_lazy?node.val:_config->initial_value;node.val=Monoid::op(x,value);node.has_lazy=true;}else{node.val=node.has_lazy?Monoid::op(x,node.val):x;node.has_lazy=true;}}intall_apply_clone(intt,Indexleft,Indexright,constT&x,boolcopy_on_write=false)const{intresult=clone_or_new(t,copy_on_write);all_apply_to_node(result,left,right,x);returnresult;}voidpush(intt,Indexleft,Indexright,boolcopy_on_write=false)const{if(!(*_pool)[t].has_lazy)return;Indexmiddle=std::midpoint(left,right);if(middle==left)return;Tlazy=(*_pool)[t].val;intleft_child=all_apply_clone((*_pool)[t].left,left,middle,lazy,copy_on_write);intright_child=all_apply_clone((*_pool)[t].right,middle,right,lazy,copy_on_write);Node&node=(*_pool)[t];_pool->replace(node.left,left_child);_pool->replace(node.right,right_child);node.val=Monoid::id();node.has_lazy=false;}intset_node(intt,Indexleft,Indexright,Indexp,Tx,boolcopy_on_write=false)const{t=clone_or_new(t,copy_on_write);Indexmiddle=std::midpoint(left,right);if(middle==left){Node&node=(*_pool)[t];node.val=std::move(x);node.has_lazy=true;returnt;}push(t,left,right,copy_on_write);if(p<middle){intchild=set_node((*_pool)[t].left,left,middle,p,std::move(x),copy_on_write);_pool->replace((*_pool)[t].left,child);}else{intchild=set_node((*_pool)[t].right,middle,right,p,std::move(x),copy_on_write);_pool->replace((*_pool)[t].right,child);}returnt;}intapply_node(intt,Indexleft,Indexright,Indexquery_left,Indexquery_right,constT&x,boolcopy_on_write=false)const{if(query_right<=left||right<=query_left)returnt;if(query_left<=left&&right<=query_right){returnall_apply_clone(t,left,right,x,copy_on_write);}t=clone_or_new(t,copy_on_write);push(t,left,right,copy_on_write);Indexmiddle=std::midpoint(left,right);intleft_child=apply_node((*_pool)[t].left,left,middle,query_left,query_right,x,copy_on_write);intright_child=apply_node((*_pool)[t].right,middle,right,query_left,query_right,x,copy_on_write);_pool->replace((*_pool)[t].left,left_child);_pool->replace((*_pool)[t].right,right_child);returnt;}Tcompose(constT&inherited,intt)const{if(!t||!(*_pool)[t].has_lazy)returninherited;returnMonoid::op(inherited,(*_pool)[t].val);}public:PersistentDynamicDualSegtree():PersistentDynamicDualSegtree(Index(0),Index(0),Monoid::id()){}explicitPersistentDynamicDualSegtree(Indexn):PersistentDynamicDualSegtree(Index(0),n,Monoid::id()){ifconstexpr(std::signed_integral<Index>)assert(Index(0)<=n);}PersistentDynamicDualSegtree(Indexleft,Indexright):PersistentDynamicDualSegtree(left,right,Monoid::id()){}PersistentDynamicDualSegtree(Indexleft,Indexright,Tinitial_value):_config(std::make_shared<Config>(left,right,std::move(initial_value))),_pool(std::make_shared<Pool>()),_root(0){}PersistentDynamicDualSegtree(constPersistentDynamicDualSegtree&other):_config(other._config),_pool(other._pool),_root(other._root){if(_pool)_pool->retain(_root);}PersistentDynamicDualSegtree(PersistentDynamicDualSegtree&&other)noexcept:_config(std::move(other._config)),_pool(std::move(other._pool)),_root(other._root){other._root=0;}PersistentDynamicDualSegtree&operator=(constPersistentDynamicDualSegtree&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_config=other._config;_pool=other._pool;_root=other._root;return*this;}PersistentDynamicDualSegtree&operator=(PersistentDynamicDualSegtree&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_config=std::move(other._config);_pool=std::move(other._pool);_root=other._root;other._root=0;return*this;}~PersistentDynamicDualSegtree(){if(_pool)_pool->release(_root);}size_typesize()const{returndetail::dynamic_distance(_config->left,_config->right);}boolempty()const{return_config->left==_config->right;}Indexleft_bound()const{return_config->left;}Indexright_bound()const{return_config->right;}constT&initial_value()const{return_config->initial_value;}voidreserve(std::size_tnode_capacity)const{assert(node_capacity<std::numeric_limits<std::size_t>::max());_pool->reserve(node_capacity);}std::size_tnode_count()const{return_pool->size();}voidrelease(){if(_pool)_pool->release(_root);_pool=std::make_shared<Pool>();_root=0;}PersistentDynamicDualSegtreeset(Indexp,Tx)const{assert(left_bound()<=p&&p<right_bound());returnPersistentDynamicDualSegtree(_config,_pool,set_node(_root,left_bound(),right_bound(),p,std::move(x)));}voidset_inplace(Indexp,Tx){assert(left_bound()<=p&&p<right_bound());introot=set_node(_root,left_bound(),right_bound(),p,std::move(x),true);_pool->replace(_root,root);}Tget(Indexp)const{assert(left_bound()<=p&&p<right_bound());intt=_root;Indexleft=left_bound();Indexright=right_bound();Tinherited=Monoid::id();while(t){Indexmiddle=std::midpoint(left,right);if(middle==left){Tvalue=(*_pool)[t].has_lazy?(*_pool)[t].val:initial_value();returnMonoid::op(inherited,value);}inherited=compose(inherited,t);if(p<middle){t=(*_pool)[t].left;right=middle;}else{t=(*_pool)[t].right;left=middle;}}returnMonoid::op(inherited,initial_value());}Toperator[](Indexp)const{returnget(p);}PersistentDynamicDualSegtreeapply(Indexp,constT&x)const{assert(left_bound()<=p&&p<right_bound());returnapply(p,p+1,x);}PersistentDynamicDualSegtreeapply(Indexleft,Indexright,constT&x)const{assert(left_bound()<=left&&left<=right&&right<=right_bound());if(left==right)return*this;returnPersistentDynamicDualSegtree(_config,_pool,apply_node(_root,left_bound(),right_bound(),left,right,x));}voidapply_inplace(Indexp,constT&x){assert(left_bound()<=p&&p<right_bound());apply_inplace(p,p+1,x);}voidapply_inplace(Indexleft,Indexright,constT&x){assert(left_bound()<=left&&left<=right&&right<=right_bound());if(left==right)return;introot=apply_node(_root,left_bound(),right_bound(),left,right,x,true);_pool->replace(_root,root);}};}// namespace ds}// namespace m1une#line 1 "ds/segtree/persistent_dynamic_lazy_segtree.hpp"
#line 13 "ds/segtree/persistent_dynamic_lazy_segtree.hpp"
#line 17 "ds/segtree/persistent_dynamic_lazy_segtree.hpp"
namespacem1une{namespaceds{// A persistent sparse lazy segment tree over an integral half-open interval.template<m1une::acted_monoid::IsActedMonoidActedMonoid,std::integralIndex=longlong>requires(!std::same_as<std::remove_cv_t<Index>,bool>)structPersistentDynamicLazySegtree{usingT=typenameActedMonoid::value_type;usingF=typenameActedMonoid::operator_type;usingindex_type=Index;usingsize_type=detail::dynamic_size_type<Index>;private:structNode{Tval;Flazy;intleft;intright;intreferences;boolhas_lazy;Node():val(ActedMonoid::id()),lazy(ActedMonoid::op_id()),left(0),right(0),references(0),has_lazy(false){}explicitNode(Tvalue):val(std::move(value)),lazy(ActedMonoid::op_id()),left(0),right(0),references(0),has_lazy(false){}};structConfig{detail::UniformMonoidDomain<ActedMonoid,Index>domain;Config(Indexleft,Indexright,Tinitial_value):domain(left,right,std::move(initial_value)){}};std::shared_ptr<constConfig>_config;usingPool=detail::PersistentNodePool<Node>;std::shared_ptr<Pool>_pool;int_root;PersistentDynamicLazySegtree(std::shared_ptr<constConfig>config,std::shared_ptr<Pool>pool,introot):_config(std::move(config)),_pool(std::move(pool)),_root(root){_pool->retain(_root);}intnew_node(Indexleft,Indexright,intdepth)const{return_pool->emplace(_config->domain.default_product(depth,left,right));}intclone_or_new(intt,Indexleft,Indexright,intdepth,boolcopy_on_write=false)const{if(!t)returnnew_node(left,right,depth);returncopy_on_write?_pool->clone_if_shared(t):_pool->clone(t);}constT&value(intt,Indexleft,Indexright,intdepth)const{if(t)return(*_pool)[t].val;return_config->domain.default_product(depth,left,right);}voidall_apply_to_node(intt,Indexleft,Indexright,constF&f)const{Node&node=(*_pool)[t];node.val=detail::dynamic_mapping<ActedMonoid>(f,node.val);if(std::midpoint(left,right)!=left){node.lazy=ActedMonoid::op_comp(f,node.lazy);node.has_lazy=true;}}intall_apply_clone(intt,Indexleft,Indexright,intdepth,constF&f,boolcopy_on_write=false)const{intresult=clone_or_new(t,left,right,depth,copy_on_write);all_apply_to_node(result,left,right,f);returnresult;}voidpush(intt,Indexleft,Indexright,intdepth,boolcopy_on_write=false)const{if(!(*_pool)[t].has_lazy)return;Indexmiddle=std::midpoint(left,right);if(middle==left)return;Flazy=(*_pool)[t].lazy;intleft_child=all_apply_clone((*_pool)[t].left,left,middle,depth+1,lazy,copy_on_write);intright_child=all_apply_clone((*_pool)[t].right,middle,right,depth+1,detail::dynamic_shift<ActedMonoid>(lazy,detail::dynamic_distance(left,middle)),copy_on_write);Node&node=(*_pool)[t];_pool->replace(node.left,left_child);_pool->replace(node.right,right_child);node.lazy=ActedMonoid::op_id();node.has_lazy=false;}voidupdate(intt,Indexleft,Indexright,intdepth)const{Indexmiddle=std::midpoint(left,right);Node&node=(*_pool)[t];node.val=ActedMonoid::op(value(node.left,left,middle,depth+1),value(node.right,middle,right,depth+1));}intset_node(intt,Indexleft,Indexright,intdepth,Indexp,Tx,boolcopy_on_write=false)const{t=clone_or_new(t,left,right,depth,copy_on_write);Indexmiddle=std::midpoint(left,right);if(middle==left){Node&node=(*_pool)[t];node.val=std::move(x);node.lazy=ActedMonoid::op_id();node.has_lazy=false;returnt;}push(t,left,right,depth,copy_on_write);if(p<middle){intchild=set_node((*_pool)[t].left,left,middle,depth+1,p,std::move(x),copy_on_write);_pool->replace((*_pool)[t].left,child);}else{intchild=set_node((*_pool)[t].right,middle,right,depth+1,p,std::move(x),copy_on_write);_pool->replace((*_pool)[t].right,child);}update(t,left,right,depth);returnt;}intapply_node(intt,Indexleft,Indexright,intdepth,Indexquery_left,Indexquery_right,constF&f,boolcopy_on_write=false)const{if(query_right<=left||right<=query_left)returnt;if(query_left<=left&&right<=query_right){returnall_apply_clone(t,left,right,depth,detail::dynamic_shift<ActedMonoid>(f,detail::dynamic_distance(query_left,left)),copy_on_write);}t=clone_or_new(t,left,right,depth,copy_on_write);push(t,left,right,depth,copy_on_write);Indexmiddle=std::midpoint(left,right);intleft_child=apply_node((*_pool)[t].left,left,middle,depth+1,query_left,query_right,f,copy_on_write);intright_child=apply_node((*_pool)[t].right,middle,right,depth+1,query_left,query_right,f,copy_on_write);_pool->replace((*_pool)[t].left,left_child);_pool->replace((*_pool)[t].right,right_child);update(t,left,right,depth);returnt;}Fcompose_for_child(constF&inherited,intt,size_typeoffset)const{Fshifted=detail::dynamic_shift<ActedMonoid>(inherited,offset);if(!t||!(*_pool)[t].has_lazy)returnshifted;returnActedMonoid::op_comp(shifted,detail::dynamic_shift<ActedMonoid>((*_pool)[t].lazy,offset));}Tprod_node(intt,Indexleft,Indexright,intdepth,Indexquery_left,Indexquery_right,constF&inherited)const{if(query_right<=left||right<=query_left)returnActedMonoid::id();if(query_left<=left&&right<=query_right){returndetail::dynamic_mapping<ActedMonoid>(inherited,value(t,left,right,depth));}Indexmiddle=std::midpoint(left,right);returnActedMonoid::op(prod_node(t?(*_pool)[t].left:0,left,middle,depth+1,query_left,query_right,compose_for_child(inherited,t,0)),prod_node(t?(*_pool)[t].right:0,middle,right,depth+1,query_left,query_right,compose_for_child(inherited,t,detail::dynamic_distance(left,middle))));}template<classG>Indexmax_right_node(intt,Indexleft,Indexright,intdepth,Indexquery_left,T&product,constF&inherited,G&predicate)const{if(right<=query_left)returnright;if(query_left<=left){Tnext=ActedMonoid::op(product,detail::dynamic_mapping<ActedMonoid>(inherited,value(t,left,right,depth)));if(predicate(next)){product=std::move(next);returnright;}Indexmiddle=std::midpoint(left,right);if(middle==left)returnleft;}Indexmiddle=std::midpoint(left,right);Indexresult=max_right_node(t?(*_pool)[t].left:0,left,middle,depth+1,query_left,product,compose_for_child(inherited,t,0),predicate);if(result<middle)returnresult;returnmax_right_node(t?(*_pool)[t].right:0,middle,right,depth+1,query_left,product,compose_for_child(inherited,t,detail::dynamic_distance(left,middle)),predicate);}template<classG>Indexmin_left_node(intt,Indexleft,Indexright,intdepth,Indexquery_right,T&product,constF&inherited,G&predicate)const{if(query_right<=left)returnleft;if(right<=query_right){Tnext=ActedMonoid::op(detail::dynamic_mapping<ActedMonoid>(inherited,value(t,left,right,depth)),product);if(predicate(next)){product=std::move(next);returnleft;}Indexmiddle=std::midpoint(left,right);if(middle==left)returnright;}Indexmiddle=std::midpoint(left,right);Indexresult=min_left_node(t?(*_pool)[t].right:0,middle,right,depth+1,query_right,product,compose_for_child(inherited,t,detail::dynamic_distance(left,middle)),predicate);if(middle<result)returnresult;returnmin_left_node(t?(*_pool)[t].left:0,left,middle,depth+1,query_right,product,compose_for_child(inherited,t,0),predicate);}public:PersistentDynamicLazySegtree():PersistentDynamicLazySegtree(Index(0),Index(0),ActedMonoid::id()){}explicitPersistentDynamicLazySegtree(Indexn):PersistentDynamicLazySegtree(Index(0),n,ActedMonoid::id()){ifconstexpr(std::signed_integral<Index>)assert(Index(0)<=n);}PersistentDynamicLazySegtree(Indexleft,Indexright):PersistentDynamicLazySegtree(left,right,ActedMonoid::id()){}PersistentDynamicLazySegtree(Indexleft,Indexright,Tinitial_value):_config(std::make_shared<Config>(left,right,std::move(initial_value))),_pool(std::make_shared<Pool>()),_root(0){}PersistentDynamicLazySegtree(constPersistentDynamicLazySegtree&other):_config(other._config),_pool(other._pool),_root(other._root){if(_pool)_pool->retain(_root);}PersistentDynamicLazySegtree(PersistentDynamicLazySegtree&&other)noexcept:_config(std::move(other._config)),_pool(std::move(other._pool)),_root(other._root){other._root=0;}PersistentDynamicLazySegtree&operator=(constPersistentDynamicLazySegtree&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_config=other._config;_pool=other._pool;_root=other._root;return*this;}PersistentDynamicLazySegtree&operator=(PersistentDynamicLazySegtree&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_config=std::move(other._config);_pool=std::move(other._pool);_root=other._root;other._root=0;return*this;}~PersistentDynamicLazySegtree(){if(_pool)_pool->release(_root);}size_typesize()const{return_config->domain.size();}boolempty()const{return_config->domain.empty();}Indexleft_bound()const{return_config->domain.left_bound();}Indexright_bound()const{return_config->domain.right_bound();}constT&initial_value()const{return_config->domain.initial_value();}voidreserve(std::size_tnode_capacity)const{assert(node_capacity<std::numeric_limits<std::size_t>::max());_pool->reserve(node_capacity);}std::size_tnode_count()const{return_pool->size();}voidrelease(){if(_pool)_pool->release(_root);_pool=std::make_shared<Pool>();_root=0;}PersistentDynamicLazySegtreeset(Indexp,Tx)const{assert(left_bound()<=p&&p<right_bound());returnPersistentDynamicLazySegtree(_config,_pool,set_node(_root,left_bound(),right_bound(),0,p,std::move(x)));}voidset_inplace(Indexp,Tx){assert(left_bound()<=p&&p<right_bound());introot=set_node(_root,left_bound(),right_bound(),0,p,std::move(x),true);_pool->replace(_root,root);}Tget(Indexp)const{assert(left_bound()<=p&&p<right_bound());returnprod(p,p+1);}Toperator[](Indexp)const{returnget(p);}Tprod(Indexleft,Indexright)const{assert(left_bound()<=left&&left<=right&&right<=right_bound());if(left==right)returnActedMonoid::id();returnprod_node(_root,left_bound(),right_bound(),0,left,right,ActedMonoid::op_id());}Tall_prod()const{returnvalue(_root,left_bound(),right_bound(),0);}PersistentDynamicLazySegtreeapply(Indexp,constF&f)const{assert(left_bound()<=p&&p<right_bound());returnapply(p,p+1,f);}PersistentDynamicLazySegtreeapply(Indexleft,Indexright,constF&f)const{assert(left_bound()<=left&&left<=right&&right<=right_bound());if(left==right)return*this;returnPersistentDynamicLazySegtree(_config,_pool,apply_node(_root,left_bound(),right_bound(),0,left,right,f));}voidapply_inplace(Indexp,constF&f){assert(left_bound()<=p&&p<right_bound());apply_inplace(p,p+1,f);}voidapply_inplace(Indexleft,Indexright,constF&f){assert(left_bound()<=left&&left<=right&&right<=right_bound());if(left==right)return;introot=apply_node(_root,left_bound(),right_bound(),0,left,right,f,true);_pool->replace(_root,root);}template<classG>Indexmax_right(Indexleft,Gpredicate)const{assert(left_bound()<=left&&left<=right_bound());assert(predicate(ActedMonoid::id()));if(left==right_bound())returnright_bound();Tproduct=ActedMonoid::id();returnmax_right_node(_root,left_bound(),right_bound(),0,left,product,ActedMonoid::op_id(),predicate);}template<classG>Indexmin_left(Indexright,Gpredicate)const{assert(left_bound()<=right&&right<=right_bound());assert(predicate(ActedMonoid::id()));if(right==left_bound())returnleft_bound();Tproduct=ActedMonoid::id();returnmin_left_node(_root,left_bound(),right_bound(),0,right,product,ActedMonoid::op_id(),predicate);}};}// namespace ds}// namespace m1une#line 1 "ds/segtree/persistent_dynamic_segtree.hpp"
#line 13 "ds/segtree/persistent_dynamic_segtree.hpp"
#line 17 "ds/segtree/persistent_dynamic_segtree.hpp"
namespacem1une{namespaceds{// A persistent sparse segment tree over an integral half-open interval.template<m1une::monoid::IsMonoidMonoid,std::integralIndex=longlong>requires(!std::same_as<std::remove_cv_t<Index>,bool>)structPersistentDynamicSegtree{usingT=typenameMonoid::value_type;usingindex_type=Index;usingsize_type=detail::dynamic_size_type<Index>;private:structNode{Tval;intleft;intright;intreferences;Node():val(Monoid::id()),left(0),right(0),references(0){}explicitNode(Tvalue):val(std::move(value)),left(0),right(0),references(0){}};structConfig{detail::UniformMonoidDomain<Monoid,Index>domain;Config(Indexleft,Indexright,Tinitial_value):domain(left,right,std::move(initial_value)){}};std::shared_ptr<constConfig>_config;usingPool=detail::PersistentNodePool<Node>;std::shared_ptr<Pool>_pool;int_root;PersistentDynamicSegtree(std::shared_ptr<constConfig>config,std::shared_ptr<Pool>pool,introot):_config(std::move(config)),_pool(std::move(pool)),_root(root){_pool->retain(_root);}intnew_node(Tvalue)const{return_pool->emplace(std::move(value));}constT&value(intt,Indexleft,Indexright,intdepth)const{if(t)return(*_pool)[t].val;return_config->domain.default_product(depth,left,right);}intset_node(intt,Indexleft,Indexright,intdepth,Indexp,Tx,boolcopy_on_write=false)const{Indexmiddle=std::midpoint(left,right);if(copy_on_write){intresult=t?_pool->clone_if_shared(t):new_node(value(0,left,right,depth));if(middle==left){(*_pool)[result].val=std::move(x);returnresult;}intchild;if(p<middle){child=set_node((*_pool)[result].left,left,middle,depth+1,p,std::move(x),true);_pool->replace((*_pool)[result].left,child);}else{child=set_node((*_pool)[result].right,middle,right,depth+1,p,std::move(x),true);_pool->replace((*_pool)[result].right,child);}Node&node=(*_pool)[result];node.val=Monoid::op(value(node.left,left,middle,depth+1),value(node.right,middle,right,depth+1));returnresult;}if(middle==left)returnnew_node(std::move(x));intleft_child=t?(*_pool)[t].left:0;intright_child=t?(*_pool)[t].right:0;if(p<middle){left_child=set_node(left_child,left,middle,depth+1,p,std::move(x));}else{right_child=set_node(right_child,middle,right,depth+1,p,std::move(x));}intresult=new_node(Monoid::op(value(left_child,left,middle,depth+1),value(right_child,middle,right,depth+1)));_pool->replace((*_pool)[result].left,left_child);_pool->replace((*_pool)[result].right,right_child);returnresult;}Tprod_node(intt,Indexleft,Indexright,intdepth,Indexquery_left,Indexquery_right)const{if(query_right<=left||right<=query_left)returnMonoid::id();if(query_left<=left&&right<=query_right){returnvalue(t,left,right,depth);}Indexmiddle=std::midpoint(left,right);returnMonoid::op(prod_node(t?(*_pool)[t].left:0,left,middle,depth+1,query_left,query_right),prod_node(t?(*_pool)[t].right:0,middle,right,depth+1,query_left,query_right));}template<classF>Indexmax_right_node(intt,Indexleft,Indexright,intdepth,Indexquery_left,T&product,F&predicate)const{if(right<=query_left)returnright;if(query_left<=left){Tnext=Monoid::op(product,value(t,left,right,depth));if(predicate(next)){product=std::move(next);returnright;}Indexmiddle=std::midpoint(left,right);if(middle==left)returnleft;}Indexmiddle=std::midpoint(left,right);Indexresult=max_right_node(t?(*_pool)[t].left:0,left,middle,depth+1,query_left,product,predicate);if(result<middle)returnresult;returnmax_right_node(t?(*_pool)[t].right:0,middle,right,depth+1,query_left,product,predicate);}template<classF>Indexmin_left_node(intt,Indexleft,Indexright,intdepth,Indexquery_right,T&product,F&predicate)const{if(query_right<=left)returnleft;if(right<=query_right){Tnext=Monoid::op(value(t,left,right,depth),product);if(predicate(next)){product=std::move(next);returnleft;}Indexmiddle=std::midpoint(left,right);if(middle==left)returnright;}Indexmiddle=std::midpoint(left,right);Indexresult=min_left_node(t?(*_pool)[t].right:0,middle,right,depth+1,query_right,product,predicate);if(middle<result)returnresult;returnmin_left_node(t?(*_pool)[t].left:0,left,middle,depth+1,query_right,product,predicate);}public:PersistentDynamicSegtree():PersistentDynamicSegtree(Index(0),Index(0),Monoid::id()){}explicitPersistentDynamicSegtree(Indexn):PersistentDynamicSegtree(Index(0),n,Monoid::id()){ifconstexpr(std::signed_integral<Index>)assert(Index(0)<=n);}PersistentDynamicSegtree(Indexleft,Indexright):PersistentDynamicSegtree(left,right,Monoid::id()){}PersistentDynamicSegtree(Indexleft,Indexright,Tinitial_value):_config(std::make_shared<Config>(left,right,std::move(initial_value))),_pool(std::make_shared<Pool>()),_root(0){}PersistentDynamicSegtree(constPersistentDynamicSegtree&other):_config(other._config),_pool(other._pool),_root(other._root){if(_pool)_pool->retain(_root);}PersistentDynamicSegtree(PersistentDynamicSegtree&&other)noexcept:_config(std::move(other._config)),_pool(std::move(other._pool)),_root(other._root){other._root=0;}PersistentDynamicSegtree&operator=(constPersistentDynamicSegtree&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_config=other._config;_pool=other._pool;_root=other._root;return*this;}PersistentDynamicSegtree&operator=(PersistentDynamicSegtree&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_config=std::move(other._config);_pool=std::move(other._pool);_root=other._root;other._root=0;return*this;}~PersistentDynamicSegtree(){if(_pool)_pool->release(_root);}size_typesize()const{return_config->domain.size();}boolempty()const{return_config->domain.empty();}Indexleft_bound()const{return_config->domain.left_bound();}Indexright_bound()const{return_config->domain.right_bound();}constT&initial_value()const{return_config->domain.initial_value();}voidreserve(std::size_tnode_capacity)const{assert(node_capacity<std::numeric_limits<std::size_t>::max());_pool->reserve(node_capacity);}std::size_tnode_count()const{return_pool->size();}voidrelease(){if(_pool)_pool->release(_root);_pool=std::make_shared<Pool>();_root=0;}PersistentDynamicSegtreeset(Indexp,Tx)const{assert(left_bound()<=p&&p<right_bound());returnPersistentDynamicSegtree(_config,_pool,set_node(_root,left_bound(),right_bound(),0,p,std::move(x)));}voidset_inplace(Indexp,Tx){assert(left_bound()<=p&&p<right_bound());introot=set_node(_root,left_bound(),right_bound(),0,p,std::move(x),true);_pool->replace(_root,root);}Tget(Indexp)const{assert(left_bound()<=p&&p<right_bound());intt=_root;Indexleft=left_bound();Indexright=right_bound();while(t){Indexmiddle=std::midpoint(left,right);if(middle==left)return(*_pool)[t].val;if(p<middle){t=(*_pool)[t].left;right=middle;}else{t=(*_pool)[t].right;left=middle;}}returninitial_value();}Toperator[](Indexp)const{returnget(p);}Tprod(Indexleft,Indexright)const{assert(left_bound()<=left&&left<=right&&right<=right_bound());if(left==right)returnMonoid::id();returnprod_node(_root,left_bound(),right_bound(),0,left,right);}Tall_prod()const{returnvalue(_root,left_bound(),right_bound(),0);}template<classF>Indexmax_right(Indexleft,Fpredicate)const{assert(left_bound()<=left&&left<=right_bound());assert(predicate(Monoid::id()));if(left==right_bound())returnright_bound();Tproduct=Monoid::id();returnmax_right_node(_root,left_bound(),right_bound(),0,left,product,predicate);}template<classF>Indexmin_left(Indexright,Fpredicate)const{assert(left_bound()<=right&&right<=right_bound());assert(predicate(Monoid::id()));if(right==left_bound())returnleft_bound();Tproduct=Monoid::id();returnmin_left_node(_root,left_bound(),right_bound(),0,right,product,predicate);}};}// namespace ds}// namespace m1une#line 1 "ds/segtree/persistent_lazy_segtree.hpp"
#line 9 "ds/segtree/persistent_lazy_segtree.hpp"
#line 12 "ds/segtree/persistent_lazy_segtree.hpp"
namespacem1une{namespaceds{template<m1une::acted_monoid::IsActedMonoidActedMonoid>structPersistentLazySegtree{usingT=typenameActedMonoid::value_type;usingF=typenameActedMonoid::operator_type;private:structNode{Tval;Flazy;intleft,right;intreferences;boolhas_lazy;Node():val(ActedMonoid::id()),lazy(ActedMonoid::op_id()),left(0),right(0),references(0),has_lazy(false){}explicitNode(Tvalue):val(std::move(value)),lazy(ActedMonoid::op_id()),left(0),right(0),references(0),has_lazy(false){}Node(Tvalue,intleft_child,intright_child):val(std::move(value)),lazy(ActedMonoid::op_id()),left(left_child),right(right_child),references(0),has_lazy(false){}};usingPool=detail::PersistentNodePool<Node>;int_n;int_root;std::shared_ptr<Pool>_pool;explicitPersistentLazySegtree(intn,introot,std::shared_ptr<Pool>pool):_n(n),_root(root),_pool(std::move(pool)){_pool->retain(_root);}intnew_node(constNode&node)const{return_pool->emplace(node);}intnew_node(Node&&node)const{return_pool->emplace(std::move(node));}intclone_node(intt)const{return_pool->clone(t);}template<typenameU>staticTmake_value(constU&value,intindex){ifconstexpr(requires(Ux){ActedMonoid::make(x);}){returnActedMonoid::make(value);}elseifconstexpr(requires(Ux,inti){ActedMonoid::make(x,i);}){returnActedMonoid::make(value,index);}else{returnstatic_cast<T>(value);}}staticTmapping_at(constF&f,constT&value,longlongord){ifconstexpr(requires(Fg,Tx,longlongi){ActedMonoid::mapping(g,x,i);}){returnActedMonoid::mapping(f,value,ord);}else{returnActedMonoid::mapping(f,value);}}staticFshift_operator(constF&f,longlongord){ifconstexpr(requires(Fg,longlongi){ActedMonoid::op_shift(g,i);}){returnActedMonoid::op_shift(f,ord);}else{returnf;}}Fcompose_for_child(constF&inherited,constNode&node,longlongord)const{Fshifted=shift_operator(inherited,ord);if(!node.has_lazy)returnshifted;returnActedMonoid::op_comp(shifted,shift_operator(node.lazy,ord));}intbuild(intl,intr,conststd::vector<T>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(v[l]));intm=(l+r)>>1;intleft=build(l,m,v);intright=build(m,r,v);returnnew_node(Node(ActedMonoid::op((*_pool)[left].val,(*_pool)[right].val),left,right));}intbuild(intl,intr,std::vector<T>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(std::move(v[l])));intm=(l+r)>>1;intleft=build(l,m,v);intright=build(m,r,v);returnnew_node(Node(ActedMonoid::op((*_pool)[left].val,(*_pool)[right].val),left,right));}template<typenameU>intbuild_from_values(intl,intr,conststd::vector<U>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(make_value(v[l],l)));intm=(l+r)>>1;intleft=build_from_values(l,m,v);intright=build_from_values(m,r,v);returnnew_node(Node(ActedMonoid::op((*_pool)[left].val,(*_pool)[right].val),left,right));}voidall_apply_to_node(intt,constF&f)const{Node&node=(*_pool)[t];node.val=mapping_at(f,node.val,0);node.lazy=ActedMonoid::op_comp(f,node.lazy);node.has_lazy=true;}intall_apply_clone(intt,constF&f,boolcopy_on_write=false)const{intres=copy_on_write?_pool->clone_if_shared(t):clone_node(t);all_apply_to_node(res,f);returnres;}voidpush(intt,intl,intr,boolcopy_on_write=false)const{if(!(*_pool)[t].has_lazy)return;Flazy=(*_pool)[t].lazy;intleft=(*_pool)[t].left;intright=(*_pool)[t].right;intm=(l+r)>>1;left=all_apply_clone(left,lazy,copy_on_write);right=all_apply_clone(right,shift_operator(lazy,m-l),copy_on_write);Node&node=(*_pool)[t];_pool->replace(node.left,left);_pool->replace(node.right,right);node.lazy=ActedMonoid::op_id();node.has_lazy=false;}voidupdate(intt)const{Node&node=(*_pool)[t];node.val=ActedMonoid::op((*_pool)[node.left].val,(*_pool)[node.right].val);}intset_node(intt,intl,intr,intp,Tvalue,boolcopy_on_write=false)const{t=copy_on_write?_pool->clone_if_shared(t):clone_node(t);if(r-l==1){Node&node=(*_pool)[t];node.val=std::move(value);node.lazy=ActedMonoid::op_id();node.has_lazy=false;returnt;}push(t,l,r,copy_on_write);intm=(l+r)>>1;if(p<m){intchild=set_node((*_pool)[t].left,l,m,p,std::move(value),copy_on_write);_pool->replace((*_pool)[t].left,child);}else{intchild=set_node((*_pool)[t].right,m,r,p,std::move(value),copy_on_write);_pool->replace((*_pool)[t].right,child);}update(t);returnt;}intapply_node(intt,intl,intr,intql,intqr,constF&f,boolcopy_on_write=false)const{if(qr<=l||r<=ql)returnt;t=copy_on_write?_pool->clone_if_shared(t):clone_node(t);if(ql<=l&&r<=qr){all_apply_to_node(t,shift_operator(f,l-ql));returnt;}push(t,l,r,copy_on_write);intm=(l+r)>>1;intleft=apply_node((*_pool)[t].left,l,m,ql,qr,f,copy_on_write);intright=apply_node((*_pool)[t].right,m,r,ql,qr,f,copy_on_write);_pool->replace((*_pool)[t].left,left);_pool->replace((*_pool)[t].right,right);update(t);returnt;}intcopy_range_node(inttarget,intsource,intl,intr,intql,intqr)const{if(qr<=l||r<=ql)returntarget;if(ql<=l&&r<=qr)returnsource;target=clone_node(target);source=clone_node(source);_pool->retain(source);push(target,l,r);push(source,l,r);intm=(l+r)>>1;intleft=copy_range_node((*_pool)[target].left,(*_pool)[source].left,l,m,ql,qr);intright=copy_range_node((*_pool)[target].right,(*_pool)[source].right,m,r,ql,qr);_pool->replace((*_pool)[target].left,left);_pool->replace((*_pool)[target].right,right);update(target);_pool->release(source);returntarget;}Tprod_node(intt,intl,intr,intql,intqr,constF&inherited)const{if(!t||qr<=l||r<=ql)returnActedMonoid::id();constNode&node=(*_pool)[t];if(ql<=l&&r<=qr)returnmapping_at(inherited,node.val,0);intm=(l+r)>>1;returnActedMonoid::op(prod_node(node.left,l,m,ql,qr,compose_for_child(inherited,node,0)),prod_node(node.right,m,r,ql,qr,compose_for_child(inherited,node,m-l)));}voidcollect_node(intt,intl,intr,intql,intqr,constF&inherited,std::vector<T>&res)const{if(!t||qr<=l||r<=ql)return;constNode&node=(*_pool)[t];if(r-l==1){res.push_back(mapping_at(inherited,node.val,0));return;}intm=(l+r)>>1;collect_node(node.left,l,m,ql,qr,compose_for_child(inherited,node,0),res);collect_node(node.right,m,r,ql,qr,compose_for_child(inherited,node,m-l),res);}template<classG>intmax_right_node(intt,intl,intr,intql,T&sm,constF&inherited,G&g)const{if(r<=ql)returnr;constNode&node=(*_pool)[t];if(ql<=l){Tnxt=ActedMonoid::op(sm,mapping_at(inherited,node.val,0));if(g(nxt)){sm=std::move(nxt);returnr;}if(r-l==1)returnl;}intm=(l+r)>>1;intres=max_right_node(node.left,l,m,ql,sm,compose_for_child(inherited,node,0),g);if(res<m)returnres;returnmax_right_node(node.right,m,r,ql,sm,compose_for_child(inherited,node,m-l),g);}template<classG>intmin_left_node(intt,intl,intr,intqr,T&sm,constF&inherited,G&g)const{if(qr<=l)returnl;constNode&node=(*_pool)[t];if(r<=qr){Tnxt=ActedMonoid::op(mapping_at(inherited,node.val,0),sm);if(g(nxt)){sm=std::move(nxt);returnl;}if(r-l==1)returnr;}intm=(l+r)>>1;intres=min_left_node(node.right,m,r,qr,sm,compose_for_child(inherited,node,m-l),g);if(m<res)returnres;returnmin_left_node(node.left,l,m,qr,sm,compose_for_child(inherited,node,0),g);}public:PersistentLazySegtree():PersistentLazySegtree(0){}explicitPersistentLazySegtree(intn):_n(n),_root(0),_pool(std::make_shared<Pool>()){assert(0<=n);if(_n>0)_root=build(0,_n,std::vector<T>(_n,ActedMonoid::id()));_pool->retain(_root);}explicitPersistentLazySegtree(conststd::vector<T>&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build(0,_n,v);_pool->retain(_root);}explicitPersistentLazySegtree(std::vector<T>&&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build(0,_n,v);_pool->retain(_root);}template<typenameU>requires(!std::same_as<U,T>)&&(requires(Ux){ActedMonoid::make(x);}||requires(Ux,inti){ActedMonoid::make(x,i);}||std::convertible_to<U,T>)explicitPersistentLazySegtree(conststd::vector<U>&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build_from_values(0,_n,v);_pool->retain(_root);}PersistentLazySegtree(constPersistentLazySegtree&other):_n(other._n),_root(other._root),_pool(other._pool){if(_pool)_pool->retain(_root);}PersistentLazySegtree(PersistentLazySegtree&&other)noexcept:_n(other._n),_root(other._root),_pool(std::move(other._pool)){other._n=0;other._root=0;}PersistentLazySegtree&operator=(constPersistentLazySegtree&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=other._pool;return*this;}PersistentLazySegtree&operator=(PersistentLazySegtree&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=std::move(other._pool);other._n=0;other._root=0;return*this;}~PersistentLazySegtree(){if(_pool)_pool->release(_root);}intsize()const{return_n;}boolempty()const{return_n==0;}voidrelease(){if(_pool)_pool->release(_root);_pool=std::make_shared<Pool>();_root=0;_n=0;}std::size_tnode_count()const{return_pool?_pool->size():0;}PersistentLazySegtreeset(intp,Tx)const{assert(0<=p&&p<_n);returnPersistentLazySegtree(_n,set_node(_root,0,_n,p,std::move(x)),_pool);}voidset_inplace(intp,Tx){assert(0<=p&&p<_n);introot=set_node(_root,0,_n,p,std::move(x),true);_pool->replace(_root,root);}Tget(intp)const{assert(0<=p&&p<_n);returnprod(p,p+1);}Toperator[](intp)const{returnget(p);}Tprod(intl,intr)const{assert(0<=l&&l<=r&&r<=_n);if(l==r)returnActedMonoid::id();returnprod_node(_root,0,_n,l,r,ActedMonoid::op_id());}Tall_prod()const{return_root?(*_pool)[_root].val:ActedMonoid::id();}std::vector<T>to_vector()const{returnto_vector(0,_n);}std::vector<T>to_vector(intl,intr)const{assert(0<=l&&l<=r&&r<=_n);std::vector<T>res;res.reserve(r-l);collect_node(_root,0,_n,l,r,ActedMonoid::op_id(),res);returnres;}PersistentLazySegtreeapply(intp,constF&f)const{assert(0<=p&&p<_n);returnapply(p,p+1,f);}PersistentLazySegtreeapply(intl,intr,constF&f)const{assert(0<=l&&l<=r&&r<=_n);if(l==r)return*this;returnPersistentLazySegtree(_n,apply_node(_root,0,_n,l,r,f),_pool);}voidapply_inplace(intp,constF&f){assert(0<=p&&p<_n);apply_inplace(p,p+1,f);}voidapply_inplace(intl,intr,constF&f){assert(0<=l&&l<=r&&r<=_n);if(l==r)return;introot=apply_node(_root,0,_n,l,r,f,true);_pool->replace(_root,root);}PersistentLazySegtreecopy_range_from(constPersistentLazySegtree&source,intl,intr)const{assert(_n==source._n);assert(_pool==source._pool);assert(0<=l&&l<=r&&r<=_n);if(l==r)return*this;introot=copy_range_node(_root,source._root,0,_n,l,r);returnPersistentLazySegtree(_n,root,_pool);}template<classG>intmax_right(intl,Gg)const{assert(0<=l&&l<=_n);assert(g(ActedMonoid::id()));if(l==_n)return_n;Tsm=ActedMonoid::id();returnmax_right_node(_root,0,_n,l,sm,ActedMonoid::op_id(),g);}template<classG>intmin_left(intr,Gg)const{assert(0<=r&&r<=_n);assert(g(ActedMonoid::id()));if(r==0)return0;Tsm=ActedMonoid::id();returnmin_left_node(_root,0,_n,r,sm,ActedMonoid::op_id(),g);}};}// namespace ds}// namespace m1une#line 1 "ds/segtree/persistent_segtree.hpp"
#line 9 "ds/segtree/persistent_segtree.hpp"
#line 12 "ds/segtree/persistent_segtree.hpp"
namespacem1une{namespaceds{template<m1une::monoid::IsMonoidMonoid>structPersistentSegtree{usingT=typenameMonoid::value_type;private:structNode{Tval;intleft,right;intreferences;Node():val(Monoid::id()),left(0),right(0),references(0){}explicitNode(Tvalue):val(std::move(value)),left(0),right(0),references(0){}Node(Tvalue,intleft_child,intright_child):val(std::move(value)),left(left_child),right(right_child),references(0){}};usingPool=detail::PersistentNodePool<Node>;int_n;int_root;std::shared_ptr<Pool>_pool;explicitPersistentSegtree(intn,introot,std::shared_ptr<Pool>pool):_n(n),_root(root),_pool(std::move(pool)){_pool->retain(_root);}intnew_node(constNode&node)const{return_pool->emplace(node);}intnew_node(Node&&node)const{return_pool->emplace(std::move(node));}template<typenameU>staticTmake_value(constU&value,intindex){ifconstexpr(requires(Ux){Monoid::make(x);}){returnMonoid::make(value);}elseifconstexpr(requires(Ux,inti){Monoid::make(x,i);}){returnMonoid::make(value,index);}else{returnstatic_cast<T>(value);}}intbuild(intl,intr,conststd::vector<T>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(v[l]));intm=(l+r)>>1;intleft=build(l,m,v);intright=build(m,r,v);returnnew_node(Node(Monoid::op(_pool->nodes[left].val,_pool->nodes[right].val),left,right));}intbuild(intl,intr,std::vector<T>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(std::move(v[l])));intm=(l+r)>>1;intleft=build(l,m,v);intright=build(m,r,v);returnnew_node(Node(Monoid::op(_pool->nodes[left].val,_pool->nodes[right].val),left,right));}template<typenameU>intbuild_from_values(intl,intr,conststd::vector<U>&v)const{if(l==r)return0;if(r-l==1)returnnew_node(Node(make_value(v[l],l)));intm=(l+r)>>1;intleft=build_from_values(l,m,v);intright=build_from_values(m,r,v);returnnew_node(Node(Monoid::op(_pool->nodes[left].val,_pool->nodes[right].val),left,right));}intset_node(intt,intl,intr,intp,Tvalue,boolcopy_on_write=false)const{if(copy_on_write)t=_pool->clone_if_shared(t);if(r-l==1){if(copy_on_write){_pool->nodes[t].val=std::move(value);returnt;}returnnew_node(Node(std::move(value)));}intm=(l+r)>>1;intleft=_pool->nodes[t].left;intright=_pool->nodes[t].right;if(p<m){left=set_node(left,l,m,p,std::move(value),copy_on_write);}else{right=set_node(right,m,r,p,std::move(value),copy_on_write);}Tproduct=Monoid::op(_pool->nodes[left].val,_pool->nodes[right].val);if(copy_on_write){_pool->replace(_pool->nodes[t].left,left);_pool->replace(_pool->nodes[t].right,right);_pool->nodes[t].val=std::move(product);returnt;}returnnew_node(Node(std::move(product),left,right));}Tprod_node(intt,intl,intr,intql,intqr)const{if(!t||qr<=l||r<=ql)returnMonoid::id();if(ql<=l&&r<=qr)return_pool->nodes[t].val;intm=(l+r)>>1;returnMonoid::op(prod_node(_pool->nodes[t].left,l,m,ql,qr),prod_node(_pool->nodes[t].right,m,r,ql,qr));}voidcollect_node(intt,intl,intr,intql,intqr,std::vector<T>&res)const{if(!t||qr<=l||r<=ql)return;if(r-l==1){res.push_back(_pool->nodes[t].val);return;}intm=(l+r)>>1;collect_node(_pool->nodes[t].left,l,m,ql,qr,res);collect_node(_pool->nodes[t].right,m,r,ql,qr,res);}template<classF>intmax_right_node(intt,intl,intr,intql,T&sm,F&f)const{if(r<=ql)returnr;if(ql<=l){Tnxt=Monoid::op(sm,_pool->nodes[t].val);if(f(nxt)){sm=std::move(nxt);returnr;}if(r-l==1)returnl;}intm=(l+r)>>1;intres=max_right_node(_pool->nodes[t].left,l,m,ql,sm,f);if(res<m)returnres;returnmax_right_node(_pool->nodes[t].right,m,r,ql,sm,f);}template<classF>intmin_left_node(intt,intl,intr,intqr,T&sm,F&f)const{if(qr<=l)returnl;if(r<=qr){Tnxt=Monoid::op(_pool->nodes[t].val,sm);if(f(nxt)){sm=std::move(nxt);returnl;}if(r-l==1)returnr;}intm=(l+r)>>1;intres=min_left_node(_pool->nodes[t].right,m,r,qr,sm,f);if(m<res)returnres;returnmin_left_node(_pool->nodes[t].left,l,m,qr,sm,f);}public:PersistentSegtree():PersistentSegtree(0){}explicitPersistentSegtree(intn):_n(n),_root(0),_pool(std::make_shared<Pool>()){assert(0<=n);if(_n>0)_root=build(0,_n,std::vector<T>(_n,Monoid::id()));_pool->retain(_root);}explicitPersistentSegtree(conststd::vector<T>&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build(0,_n,v);_pool->retain(_root);}explicitPersistentSegtree(std::vector<T>&&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build(0,_n,v);_pool->retain(_root);}template<typenameU>requires(!std::same_as<U,T>)&&(requires(Ux){Monoid::make(x);}||requires(Ux,inti){Monoid::make(x,i);}||std::convertible_to<U,T>)explicitPersistentSegtree(conststd::vector<U>&v):_n(int(v.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(v.size()*2);if(_n>0)_root=build_from_values(0,_n,v);_pool->retain(_root);}PersistentSegtree(constPersistentSegtree&other):_n(other._n),_root(other._root),_pool(other._pool){if(_pool)_pool->retain(_root);}PersistentSegtree(PersistentSegtree&&other)noexcept:_n(other._n),_root(other._root),_pool(std::move(other._pool)){other._n=0;other._root=0;}PersistentSegtree&operator=(constPersistentSegtree&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=other._pool;return*this;}PersistentSegtree&operator=(PersistentSegtree&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=std::move(other._pool);other._n=0;other._root=0;return*this;}~PersistentSegtree(){if(_pool)_pool->release(_root);}intsize()const{return_n;}boolempty()const{return_n==0;}// Drops this version immediately. Other versions and shared nodes stay valid.voidrelease(){if(_pool)_pool->release(_root);_pool=std::make_shared<Pool>();_root=0;_n=0;}std::size_tnode_count()const{return_pool?_pool->size():0;}PersistentSegtreeset(intp,Tx)const{assert(0<=p&&p<_n);returnPersistentSegtree(_n,set_node(_root,0,_n,p,std::move(x)),_pool);}voidset_inplace(intp,Tx){assert(0<=p&&p<_n);introot=set_node(_root,0,_n,p,std::move(x),true);_pool->replace(_root,root);}Tget(intp)const{assert(0<=p&&p<_n);intt=_root;intl=0,r=_n;while(r-l>1){intm=(l+r)>>1;if(p<m){t=_pool->nodes[t].left;r=m;}else{t=_pool->nodes[t].right;l=m;}}return_pool->nodes[t].val;}Toperator[](intp)const{returnget(p);}Tprod(intl,intr)const{assert(0<=l&&l<=r&&r<=_n);if(l==r)returnMonoid::id();returnprod_node(_root,0,_n,l,r);}Tall_prod()const{return_root?_pool->nodes[_root].val:Monoid::id();}std::vector<T>to_vector()const{returnto_vector(0,_n);}std::vector<T>to_vector(intl,intr)const{assert(0<=l&&l<=r&&r<=_n);std::vector<T>res;res.reserve(r-l);collect_node(_root,0,_n,l,r,res);returnres;}template<classF>intmax_right(intl,Ff)const{assert(0<=l&&l<=_n);assert(f(Monoid::id()));if(l==_n)return_n;Tsm=Monoid::id();returnmax_right_node(_root,0,_n,l,sm,f);}template<classF>intmin_left(intr,Ff)const{assert(0<=r&&r<=_n);assert(f(Monoid::id()));if(r==0)return0;Tsm=Monoid::id();returnmin_left_node(_root,0,_n,r,sm,f);}};}// namespace ds}// namespace m1une#line 1 "ds/segtree/persistent_segtree_beats.hpp"
#line 10 "ds/segtree/persistent_segtree_beats.hpp"
#line 1 "beats_acted_monoid/concept.hpp"
#line 5 "beats_acted_monoid/concept.hpp"
#line 7 "beats_acted_monoid/concept.hpp"
namespacem1une{namespacebeats_acted_monoid{// An acted monoid whose action may require descent before it can be applied.template<typenameAM>conceptIsBeatsActedMonoid=m1une::acted_monoid::IsActedMonoid<AM>&&requires(typenameAM::value_typex,typenameAM::operator_typef){{AM::can_apply(f,x)}->std::same_as<bool>;};}// namespace beats_acted_monoid}// namespace m1une#line 13 "ds/segtree/persistent_segtree_beats.hpp"
namespacem1une{namespaceds{// A persistent Segment Tree Beats for fallible monoid actions.template<m1une::beats_acted_monoid::IsBeatsActedMonoidActedMonoid>structPersistentSegtreeBeats{usingvalue_type=typenameActedMonoid::value_type;usingoperator_type=typenameActedMonoid::operator_type;usingT=value_type;usingF=operator_type;private:structNode{Tval;Flazy;intleft;intright;intreferences;boolhas_lazy;Node():val(ActedMonoid::id()),lazy(ActedMonoid::op_id()),left(0),right(0),references(0),has_lazy(false){}explicitNode(Tvalue):val(std::move(value)),lazy(ActedMonoid::op_id()),left(0),right(0),references(0),has_lazy(false){}Node(Tvalue,intleft_child,intright_child):val(std::move(value)),lazy(ActedMonoid::op_id()),left(left_child),right(right_child),references(0),has_lazy(false){}};usingPool=detail::PersistentNodePool<Node>;int_n;int_root;std::shared_ptr<Pool>_pool;explicitPersistentSegtreeBeats(intn,introot,std::shared_ptr<Pool>pool):_n(n),_root(root),_pool(std::move(pool)){_pool->retain(_root);}intnew_node(constNode&node)const{return_pool->emplace(node);}intnew_node(Node&&node)const{return_pool->emplace(std::move(node));}intclone_node(intnode)const{return_pool->clone(node);}template<typenameU>staticTmake_value(constU&value,intindex){ifconstexpr(requires(Ux){ActedMonoid::make(x);}){returnActedMonoid::make(value);}elseifconstexpr(requires(Ux,inti){ActedMonoid::make(x,i);}){returnActedMonoid::make(value,index);}else{returnstatic_cast<T>(value);}}staticTmapping_at(constF&f,constT&value,longlongordinal){ifconstexpr(requires(Fg,Tx,longlongi){ActedMonoid::mapping(g,x,i);}){returnActedMonoid::mapping(f,value,ordinal);}else{returnActedMonoid::mapping(f,value);}}staticboolcan_apply_at(constF&f,constT&value,longlongordinal){ifconstexpr(requires(Fg,Tx,longlongi){ActedMonoid::can_apply(g,x,i);}){returnActedMonoid::can_apply(f,value,ordinal);}else{returnActedMonoid::can_apply(f,value);}}staticFshift_operator(constF&f,longlongordinal){ifconstexpr(requires(Fg,longlongi){ActedMonoid::op_shift(g,i);}){returnActedMonoid::op_shift(f,ordinal);}else{returnf;}}intbuild(intleft,intright,conststd::vector<T>&values)const{if(left==right)return0;if(right-left==1)returnnew_node(Node(values[left]));intmiddle=left+(right-left)/2;intleft_child=build(left,middle,values);intright_child=build(middle,right,values);returnnew_node(Node(ActedMonoid::op((*_pool)[left_child].val,(*_pool)[right_child].val),left_child,right_child));}intbuild(intleft,intright,std::vector<T>&values)const{if(left==right)return0;if(right-left==1){returnnew_node(Node(std::move(values[left])));}intmiddle=left+(right-left)/2;intleft_child=build(left,middle,values);intright_child=build(middle,right,values);returnnew_node(Node(ActedMonoid::op((*_pool)[left_child].val,(*_pool)[right_child].val),left_child,right_child));}template<typenameU>intbuild_from_values(intleft,intright,conststd::vector<U>&values)const{if(left==right)return0;if(right-left==1){returnnew_node(Node(make_value(values[left],left)));}intmiddle=left+(right-left)/2;intleft_child=build_from_values(left,middle,values);intright_child=build_from_values(middle,right,values);returnnew_node(Node(ActedMonoid::op((*_pool)[left_child].val,(*_pool)[right_child].val),left_child,right_child));}voidupdate(intnode)const{Node¤t=(*_pool)[node];current.val=ActedMonoid::op((*_pool)[current.left].val,(*_pool)[current.right].val);}intall_apply_clone(intnode,intleft,intright,constF&f,boolcopy_on_write=false)const{intresult=copy_on_write?_pool->clone_if_shared(node):clone_node(node);Node¤t=(*_pool)[result];if(can_apply_at(f,current.val,0)){current.val=mapping_at(f,current.val,0);if(right-left>1){current.lazy=ActedMonoid::op_comp(f,current.lazy);current.has_lazy=true;}returnresult;}assert(right-left>1);push(result,left,right,copy_on_write);intmiddle=left+(right-left)/2;intleft_child=all_apply_clone((*_pool)[result].left,left,middle,f,copy_on_write);intright_child=all_apply_clone((*_pool)[result].right,middle,right,shift_operator(f,middle-left),copy_on_write);_pool->replace((*_pool)[result].left,left_child);_pool->replace((*_pool)[result].right,right_child);update(result);returnresult;}voidpush(intnode,intleft,intright,boolcopy_on_write=false)const{if(!(*_pool)[node].has_lazy)return;assert(right-left>1);Flazy=(*_pool)[node].lazy;intmiddle=left+(right-left)/2;intleft_child=all_apply_clone((*_pool)[node].left,left,middle,lazy,copy_on_write);intright_child=all_apply_clone((*_pool)[node].right,middle,right,shift_operator(lazy,middle-left),copy_on_write);_pool->replace((*_pool)[node].left,left_child);_pool->replace((*_pool)[node].right,right_child);Node¤t=(*_pool)[node];current.lazy=ActedMonoid::op_id();current.has_lazy=false;}intset_node(intnode,intleft,intright,intindex,Tvalue,boolcopy_on_write=false)const{intresult=copy_on_write?_pool->clone_if_shared(node):clone_node(node);if(right-left==1){Node¤t=(*_pool)[result];current.val=std::move(value);current.lazy=ActedMonoid::op_id();current.has_lazy=false;returnresult;}push(result,left,right,copy_on_write);intmiddle=left+(right-left)/2;if(index<middle){intchild=set_node((*_pool)[result].left,left,middle,index,std::move(value),copy_on_write);_pool->replace((*_pool)[result].left,child);}else{intchild=set_node((*_pool)[result].right,middle,right,index,std::move(value),copy_on_write);_pool->replace((*_pool)[result].right,child);}update(result);returnresult;}intapply_node(intnode,intleft,intright,intquery_left,intquery_right,constF&f,boolcopy_on_write=false)const{if(query_right<=left||right<=query_left)returnnode;if(query_left<=left&&right<=query_right){returnall_apply_clone(node,left,right,shift_operator(f,left-query_left),copy_on_write);}intresult=copy_on_write?_pool->clone_if_shared(node):clone_node(node);push(result,left,right,copy_on_write);intmiddle=left+(right-left)/2;intleft_child=apply_node((*_pool)[result].left,left,middle,query_left,query_right,f,copy_on_write);intright_child=apply_node((*_pool)[result].right,middle,right,query_left,query_right,f,copy_on_write);_pool->replace((*_pool)[result].left,left_child);_pool->replace((*_pool)[result].right,right_child);update(result);returnresult;}intcopy_range_node(inttarget,intsource,intleft,intright,intquery_left,intquery_right)const{if(query_right<=left||right<=query_left)returntarget;if(query_left<=left&&right<=query_right)returnsource;intresult=clone_node(target);intmaterialized_source=clone_node(source);_pool->retain(materialized_source);push(result,left,right);push(materialized_source,left,right);intmiddle=left+(right-left)/2;intleft_child=copy_range_node((*_pool)[result].left,(*_pool)[materialized_source].left,left,middle,query_left,query_right);intright_child=copy_range_node((*_pool)[result].right,(*_pool)[materialized_source].right,middle,right,query_left,query_right);_pool->replace((*_pool)[result].left,left_child);_pool->replace((*_pool)[result].right,right_child);update(result);_pool->release(materialized_source);returnresult;}Fcompose_for_child(constF&inherited,constNode&node,longlongordinal)const{Fshifted=shift_operator(inherited,ordinal);if(!node.has_lazy)returnshifted;returnActedMonoid::op_comp(shifted,shift_operator(node.lazy,ordinal));}Tevaluate_node(intnode,intleft,intright,constF&inherited)const{constNode¤t=(*_pool)[node];if(can_apply_at(inherited,current.val,0)){returnmapping_at(inherited,current.val,0);}assert(right-left>1);intmiddle=left+(right-left)/2;returnActedMonoid::op(evaluate_node(current.left,left,middle,compose_for_child(inherited,current,0)),evaluate_node(current.right,middle,right,compose_for_child(inherited,current,middle-left)));}Tprod_node(intnode,intleft,intright,intquery_left,intquery_right,constF&inherited)const{if(query_right<=left||right<=query_left){returnActedMonoid::id();}if(query_left<=left&&right<=query_right){returnevaluate_node(node,left,right,inherited);}constNode¤t=(*_pool)[node];intmiddle=left+(right-left)/2;returnActedMonoid::op(prod_node(current.left,left,middle,query_left,query_right,compose_for_child(inherited,current,0)),prod_node(current.right,middle,right,query_left,query_right,compose_for_child(inherited,current,middle-left)));}voidcollect_node(intnode,intleft,intright,intquery_left,intquery_right,constF&inherited,std::vector<T>&result)const{if(query_right<=left||right<=query_left)return;constNode¤t=(*_pool)[node];if(right-left==1){result.push_back(mapping_at(inherited,current.val,0));return;}intmiddle=left+(right-left)/2;collect_node(current.left,left,middle,query_left,query_right,compose_for_child(inherited,current,0),result);collect_node(current.right,middle,right,query_left,query_right,compose_for_child(inherited,current,middle-left),result);}template<classPredicate>intmax_right_node(intnode,intleft,intright,intquery_left,T&product,constF&inherited,Predicate&predicate)const{if(right<=query_left)returnright;if(query_left<=left){Tnext=ActedMonoid::op(product,evaluate_node(node,left,right,inherited));if(predicate(next)){product=std::move(next);returnright;}if(right-left==1)returnleft;}constNode¤t=(*_pool)[node];intmiddle=left+(right-left)/2;intresult=max_right_node(current.left,left,middle,query_left,product,compose_for_child(inherited,current,0),predicate);if(result<middle)returnresult;returnmax_right_node(current.right,middle,right,query_left,product,compose_for_child(inherited,current,middle-left),predicate);}template<classPredicate>intmin_left_node(intnode,intleft,intright,intquery_right,T&product,constF&inherited,Predicate&predicate)const{if(query_right<=left)returnleft;if(right<=query_right){Tnext=ActedMonoid::op(evaluate_node(node,left,right,inherited),product);if(predicate(next)){product=std::move(next);returnleft;}if(right-left==1)returnright;}constNode¤t=(*_pool)[node];intmiddle=left+(right-left)/2;intresult=min_left_node(current.right,middle,right,query_right,product,compose_for_child(inherited,current,middle-left),predicate);if(middle<result)returnresult;returnmin_left_node(current.left,left,middle,query_right,product,compose_for_child(inherited,current,0),predicate);}public:PersistentSegtreeBeats():PersistentSegtreeBeats(0){}explicitPersistentSegtreeBeats(intn):_n(n),_root(0),_pool(std::make_shared<Pool>()){assert(0<=n);if(_n>0){std::vector<T>values(_n,ActedMonoid::id());_root=build(0,_n,values);}_pool->retain(_root);}explicitPersistentSegtreeBeats(conststd::vector<T>&values):_n(int(values.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(values.size()*2);if(_n>0)_root=build(0,_n,values);_pool->retain(_root);}explicitPersistentSegtreeBeats(std::vector<T>&&values):_n(int(values.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(values.size()*2);if(_n>0)_root=build(0,_n,values);_pool->retain(_root);}template<typenameU>requires(!std::same_as<U,T>)&&(requires(Ux){ActedMonoid::make(x);}||requires(Ux,inti){ActedMonoid::make(x,i);}||std::convertible_to<U,T>)explicitPersistentSegtreeBeats(conststd::vector<U>&values):_n(int(values.size())),_root(0),_pool(std::make_shared<Pool>()){_pool->reserve(values.size()*2);if(_n>0)_root=build_from_values(0,_n,values);_pool->retain(_root);}PersistentSegtreeBeats(constPersistentSegtreeBeats&other):_n(other._n),_root(other._root),_pool(other._pool){if(_pool)_pool->retain(_root);}PersistentSegtreeBeats(PersistentSegtreeBeats&&other)noexcept:_n(other._n),_root(other._root),_pool(std::move(other._pool)){other._n=0;other._root=0;}PersistentSegtreeBeats&operator=(constPersistentSegtreeBeats&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._root);if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=other._pool;return*this;}PersistentSegtreeBeats&operator=(PersistentSegtreeBeats&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_root);_n=other._n;_root=other._root;_pool=std::move(other._pool);other._n=0;other._root=0;return*this;}~PersistentSegtreeBeats(){if(_pool)_pool->release(_root);}intsize()const{return_n;}boolempty()const{return_n==0;}voidrelease(){if(_pool)_pool->release(_root);_pool=std::make_shared<Pool>();_root=0;_n=0;}std::size_tnode_count()const{return_pool?_pool->size():0;}PersistentSegtreeBeatsset(intindex,Tvalue)const{assert(0<=index&&index<_n);returnPersistentSegtreeBeats(_n,set_node(_root,0,_n,index,std::move(value)),_pool);}voidset_inplace(intindex,Tvalue){assert(0<=index&&index<_n);introot=set_node(_root,0,_n,index,std::move(value),true);_pool->replace(_root,root);}Tget(intindex)const{assert(0<=index&&index<_n);returnprod(index,index+1);}Toperator[](intindex)const{returnget(index);}Tprod(intleft,intright)const{assert(0<=left&&left<=right&&right<=_n);if(left==right)returnActedMonoid::id();returnprod_node(_root,0,_n,left,right,ActedMonoid::op_id());}Tall_prod()const{return_root?(*_pool)[_root].val:ActedMonoid::id();}PersistentSegtreeBeatsapply(intindex,constF&f)const{assert(0<=index&&index<_n);returnapply(index,index+1,f);}PersistentSegtreeBeatsapply(intleft,intright,constF&f)const{assert(0<=left&&left<=right&&right<=_n);if(left==right)return*this;returnPersistentSegtreeBeats(_n,apply_node(_root,0,_n,left,right,f),_pool);}voidapply_inplace(intindex,constF&f){assert(0<=index&&index<_n);apply_inplace(index,index+1,f);}voidapply_inplace(intleft,intright,constF&f){assert(0<=left&&left<=right&&right<=_n);if(left==right)return;introot=apply_node(_root,0,_n,left,right,f,true);_pool->replace(_root,root);}PersistentSegtreeBeatscopy_range_from(constPersistentSegtreeBeats&source,intleft,intright)const{assert(_n==source._n);assert(_pool==source._pool);assert(0<=left&&left<=right&&right<=_n);if(left==right)return*this;returnPersistentSegtreeBeats(_n,copy_range_node(_root,source._root,0,_n,left,right),_pool);}std::vector<T>to_vector()const{returnto_vector(0,_n);}std::vector<T>to_vector(intleft,intright)const{assert(0<=left&&left<=right&&right<=_n);std::vector<T>result;result.reserve(right-left);if(left!=right){collect_node(_root,0,_n,left,right,ActedMonoid::op_id(),result);}returnresult;}template<classPredicate>intmax_right(intleft,Predicatepredicate)const{assert(0<=left&&left<=_n);assert(predicate(ActedMonoid::id()));if(left==_n)return_n;Tproduct=ActedMonoid::id();returnmax_right_node(_root,0,_n,left,product,ActedMonoid::op_id(),predicate);}template<classPredicate>intmin_left(intright,Predicatepredicate)const{assert(0<=right&&right<=_n);assert(predicate(ActedMonoid::id()));if(right==0)return0;Tproduct=ActedMonoid::id();returnmin_left_node(_root,0,_n,right,product,ActedMonoid::op_id(),predicate);}};}// namespace ds}// namespace m1une#line 1 "monoid/add.hpp"
namespacem1une{namespacemonoid{// Monoid for addition (Range Sum).template<typenameT>structAdd{usingvalue_type=T;staticconstexprboolcommutative=true;// Returns the identity element for addition, which is 0.staticconstexprTid(){returnT(0);}// Returns the sum of a and b.staticconstexprTop(constT&a,constT&b){returna+b;}staticconstexprTinv(constT&x){return-x;}};}// namespace monoid}// namespace m1une#line 1 "utilities/fast_io.hpp"
#line 5 "utilities/fast_io.hpp"
#include<array>
#include<cerrno>
#include<charconv>
#line 9 "utilities/fast_io.hpp"
#include<cstdio>
#include<cstdlib>
#line 12 "utilities/fast_io.hpp"
#include<cstring>
#include<iterator>
#include<string>
#include<sys/stat.h>
#line 18 "utilities/fast_io.hpp"
#include<unistd.h>
#line 20 "utilities/fast_io.hpp"
namespacem1une{namespaceutilities{structFastOutput;namespaceinternal{// Shared with the convenience helpers in template.hpp.inlineFastOutput*standard_output_instance=nullptr;// Detect std::begin(x), std::end(x).template<classT,class=void>structis_range:std::false_type{};template<classT>structis_range<T,std::void_t<decltype(std::begin(std::declval<T&>())),decltype(std::end(std::declval<T&>()))>>:std::true_type{};template<classT>inlineconstexprboolis_range_v=is_range<T>::value;template<classT>usingrange_reference_t=decltype(*std::begin(std::declval<T&>()));template<classT>usingrange_value_t=std::remove_cv_t<std::remove_reference_t<range_reference_t<T>>>;template<classT,class=void>structrange_stored_value{usingtype=range_value_t<T>;};template<classT>structrange_stored_value<T,std::void_t<typenamestd::remove_cv_t<std::remove_reference_t<T>>::value_type>>{usingtype=typenamestd::remove_cv_t<std::remove_reference_t<T>>::value_type;};template<classT>usingrange_stored_value_t=typenamerange_stored_value<T>::type;// Treat strings and C strings as scalar output objects, not as ranges.template<classT>structis_char_array:std::false_type{};template<classT,std::size_tN>structis_char_array<T[N]>:std::bool_constant<std::is_same_v<std::remove_cv_t<T>,char>>{};template<classT>structis_string_like:std::bool_constant<std::is_same_v<std::decay_t<T>,std::string>||std::is_same_v<std::decay_t<T>,constchar*>||std::is_same_v<std::decay_t<T>,char*>||is_char_array<std::remove_reference_t<T>>::value>{};template<classT>inlineconstexprboolis_string_like_v=is_string_like<T>::value;// ModInt-like type: x.val() is printable, and x can be assigned from long long.template<classT,class=void>structhas_val_method:std::false_type{};template<classT>structhas_val_method<T,std::void_t<decltype(std::declval<constT&>().val())>>:std::true_type{};template<classT>inlineconstexprboolhas_val_method_v=has_val_method<T>::value;template<classT,class=void>structhas_static_mod_raw:std::false_type{};template<classT>structhas_static_mod_raw<T,std::void_t<decltype(T::mod()),decltype(T::raw(std::declval<uint32_t>()))>>:std::true_type{};template<classT>inlineconstexprboolhas_static_mod_raw_v=has_static_mod_raw<T>::value;// libstdc++ before GCC 16 does not classify __int128 as an integral type in// strict ISO modes such as -std=c++23. Keep the fast-I/O interface independent// of that implementation detail.template<classT>inlineconstexprboolis_integral_v=std::is_integral_v<T>||std::is_same_v<std::remove_cv_t<T>,__int128_t>||std::is_same_v<std::remove_cv_t<T>,__uint128_t>;template<classT>inlineconstexprboolis_signed_v=std::is_signed_v<T>||std::is_same_v<std::remove_cv_t<T>,__int128_t>;template<classT>structmake_unsigned{usingtype=std::make_unsigned_t<T>;};template<>structmake_unsigned<__int128_t>{usingtype=__uint128_t;};template<>structmake_unsigned<__uint128_t>{usingtype=__uint128_t;};template<classT>usingmake_unsigned_t=typenamemake_unsigned<std::remove_cv_t<T>>::type;}// namespace internalstructFastInput{staticconstexprintbuffer_size=1<<20;private:std::FILE*_stream;char_buffer[buffer_size];int_position;int_length;int_file_descriptor;bool_streaming;boolrefill(){_position=0;if(_streaming){ssize_tlength;do{length=::read(_file_descriptor,_buffer,buffer_size);}while(length<0&&errno==EINTR);if(length<=0){_length=0;returnfalse;}_length=int(length);}else{_length=int(std::fread(_buffer,1,buffer_size,_stream));}return_length!=0;}template<classT>boolread_integer_from_stream(T&value){if(!skip_spaces())returnfalse;intc=read_char_raw();boolnegative=false;if(c=='-'){negative=true;c=read_char_raw();}ifconstexpr(internal::is_signed_v<T>){Tresult=0;while('0'<=c&&c<='9'){result=negative?result*10-(c-'0'):result*10+(c-'0');c=read_char_raw();}value=result;}else{Tresult=0;while('0'<=c&&c<='9'){result=result*10+T(c-'0');c=read_char_raw();}value=negative?T(0)-result:result;}returntrue;}boolprepare_number(){if(_length-_position>=64)returntrue;constintremaining=_length-_position;if(remaining>0)std::memmove(_buffer,_buffer+_position,remaining);constintadded=int(std::fread(_buffer+remaining,1,buffer_size-remaining,_stream));_position=0;_length=remaining+added;if(_length<buffer_size)_buffer[_length]='\0';return_length!=0;}public:explicitFastInput(std::FILE*stream=stdin):_stream(stream),_position(0),_length(0),_file_descriptor(::fileno(stream)),_streaming([&]{structstatstatus;return_file_descriptor>=0&&::fstat(_file_descriptor,&status)==0&&!S_ISREG(status.st_mode);}()){}FastInput(constFastInput&)=delete;FastInput&operator=(constFastInput&)=delete;intread_char_raw(){if(_position==_length&&!refill())returnEOF;return_buffer[_position++];}boolskip_spaces(){intc=read_char_raw();while(c!=EOF&&c<=' ')c=read_char_raw();if(c==EOF)returnfalse;--_position;returntrue;}boolread(char&value){if(!skip_spaces())returnfalse;value=char(read_char_raw());returntrue;}boolread(std::string&value){if(!skip_spaces())returnfalse;value.clear();while(true){constintbegin=_position;while(_position<_length&&static_cast<unsignedchar>(_buffer[_position])>' '){++_position;}value.append(_buffer+begin,_position-begin);if(_position<_length){++_position;returntrue;}if(!refill())returntrue;}}boolread(bool&value){intx;if(!read(x))returnfalse;value=x!=0;returntrue;}template<classT>std::enable_if_t<internal::is_integral_v<T>&&!std::is_same_v<std::remove_cv_t<T>,bool>&&!std::is_same_v<std::remove_cv_t<T>,char>,bool>read(T&value){if(_streaming)returnread_integer_from_stream(value);if(!prepare_number())returnfalse;intc=static_cast<unsignedchar>(_buffer[_position++]);while(c<=' ')c=static_cast<unsignedchar>(_buffer[_position++]);boolnegative=false;if(c=='-'){negative=true;c=static_cast<unsignedchar>(_buffer[_position++]);}ifconstexpr(internal::is_signed_v<T>){Tresult=0;while('0'<=c&&c<='9'){constintfirst=c-'0';constintsecond=static_cast<unsignedchar>(_buffer[_position])-'0';if(0<=second&&second<=9){result=negative?result*100-(first*10+second):result*100+(first*10+second);++_position;}else{result=negative?result*10-first:result*10+first;}c=static_cast<unsignedchar>(_buffer[_position++]);}value=result;}else{Tresult=0;while('0'<=c&&c<='9'){constunsignedfirst=unsigned(c-'0');constintsecond=static_cast<unsignedchar>(_buffer[_position])-'0';if(0<=second&&second<=9){result=result*100+T(first*10+unsigned(second));++_position;}else{result=result*10+T(first);}c=static_cast<unsignedchar>(_buffer[_position++]);}value=negative?T(0)-result:result;}if(_position>_length)_position=_length;returntrue;}template<classT>std::enable_if_t<std::is_floating_point_v<T>,bool>read(T&value){if(!skip_spaces())returnfalse;intc=read_char_raw();boolnegative=false;if(c=='-'||c=='+'){negative=c=='-';c=read_char_raw();}longdoubleresult=0;while('0'<=c&&c<='9'){result=result*10+(c-'0');c=read_char_raw();}if(c=='.'){longdoubleplace=0.1L;c=read_char_raw();while('0'<=c&&c<='9'){result+=(c-'0')*place;place*=0.1L;c=read_char_raw();}}if(c=='e'||c=='E'){c=read_char_raw();boolexponent_negative=false;if(c=='-'||c=='+'){exponent_negative=c=='-';c=read_char_raw();}intexponent=0;while('0'<=c&&c<='9'){exponent=exponent*10+(c-'0');c=read_char_raw();}longdoublescale=1;longdoublepower=10;while(exponent>0){if(exponent&1)scale*=power;power*=power;exponent>>=1;}result=exponent_negative?result/scale:result*scale;}value=static_cast<T>(negative?-result:result);returntrue;}template<classT>std::enable_if_t<internal::has_val_method_v<T>&&!internal::is_integral_v<T>&&!internal::is_range_v<T>,bool>read(T&value){longlongx;if(!read(x))returnfalse;ifconstexpr(internal::has_static_mod_raw_v<T>){if(x>=0&&uint64_t(x)<uint64_t(T::mod())){value=T::raw(uint32_t(x));}else{value=T(x);}}else{value=T(x);}returntrue;}template<classFirst,classSecond>boolread(std::pair<First,Second>&value){if(!read(value.first))returnfalse;returnread(value.second);}template<classRange>std::enable_if_t<internal::is_range_v<Range>&&!internal::is_string_like_v<Range>,bool>read(Range&range){usingStoredValue=internal::range_stored_value_t<Range>;constexprboolnested=internal::is_range_v<StoredValue>&&!internal::is_string_like_v<StoredValue>;for(auto&&value:range){ifconstexpr(std::is_same_v<StoredValue,bool>&&!nested){boolx;if(!read(x))returnfalse;value=x;}else{if(!read(value))returnfalse;}}returntrue;}template<classFirst,classSecond,class...Rest>boolread(First&first,Second&second,Rest&...rest){if(!read(first))returnfalse;returnread(second,rest...);}template<classT>FastInput&operator>>(T&value){if(!read(value))std::abort();return*this;}};structFastOutput{staticconstexprintbuffer_size=1<<20;private:inlinestaticconstautodigit_quads=[]{std::array<char,40000>result{};for(inti=0;i<10000;i++){intvalue=i;for(intj=3;j>=0;j--){result[4*i+j]=char('0'+value%10);value/=10;}}returnresult;}();std::FILE*_stream;char_buffer[buffer_size];int_position;int_precision;std::chars_format_float_format;char_range_separator;std::string*_capture=nullptr;template<classT>std::stringformat_cell(constT&value){std::stringresult;structCaptureGuard{std::string*⌖std::string*previous;~CaptureGuard(){target=previous;}}guard{_capture,_capture};_capture=&result;write(value);returnresult;}template<classMatrix>voidwrite_aligned_matrix(constMatrix&matrix){std::vector<std::vector<std::string>>rows;std::vector<std::size_t>widths;for(constauto&row:matrix){auto&cells=rows.emplace_back();std::size_tcolumn=0;for(constauto&value:row){cells.push_back(format_cell(value));if(column==widths.size())widths.push_back(0);widths[column]=std::max(widths[column],cells.back().size());++column;}}boolfirst=true;for(constauto&row:rows){if(!first)write_char('\n');first=false;for(std::size_tcolumn=0;column<row.size();++column){if(column!=0)write_char(_range_separator);for(std::size_tpadding=row[column].size();padding<widths[column];++padding){write_char(' ');}write(row[column]);}}}public:explicitFastOutput(std::FILE*stream=stdout):_stream(stream),_position(0),_precision(6),_float_format(std::chars_format::general),_range_separator(' '){if(_stream==stdout&&internal::standard_output_instance==nullptr){internal::standard_output_instance=this;}}FastOutput(constFastOutput&)=delete;FastOutput&operator=(constFastOutput&)=delete;~FastOutput(){flush();if(internal::standard_output_instance==this){internal::standard_output_instance=nullptr;}}voidflush(){if(_position!=0){std::fwrite(_buffer,1,_position,_stream);_position=0;}std::fflush(_stream);}voidwrite_char(charc){if(_capture!=nullptr){_capture->push_back(c);return;}if(_position==buffer_size)flush();_buffer[_position++]=c;}voidwrite(constchar*s){while(*s!='\0')write_char(*s++);}voidwrite(conststd::string&s){if(_capture!=nullptr){_capture->append(s);return;}std::size_tposition=0;while(position<s.size()){if(_position==buffer_size)flush();conststd::size_tcopied=std::min<std::size_t>(buffer_size-_position,s.size()-position);std::memcpy(_buffer+_position,s.data()+position,copied);_position+=int(copied);position+=copied;}}voidwrite(charc){write_char(c);}voidwrite(boolvalue){write_char(value?'1':'0');}template<classT>std::enable_if_t<std::is_floating_point_v<T>>write(Tvalue){chardigits[128];auto[end,error]=std::to_chars(digits,digits+sizeof(digits),value,_float_format,_precision);if(error!=std::errc())std::abort();for(constchar*pointer=digits;pointer!=end;pointer++){write_char(*pointer);}}template<classT>std::enable_if_t<internal::is_integral_v<T>&&!std::is_same_v<std::remove_cv_t<T>,bool>&&!std::is_same_v<std::remove_cv_t<T>,char>>write(Tvalue){usingRaw=std::remove_cv_t<T>;usingUnsigned=internal::make_unsigned_t<Raw>;Unsignedmagnitude;ifconstexpr(internal::is_signed_v<Raw>){if(value<0){write_char('-');magnitude=Unsigned(0)-Unsigned(value);}else{magnitude=Unsigned(value);}}else{magnitude=value;}if(magnitude==0){write_char('0');return;}unsignedchunks[16];intcount=0;while(magnitude>=10000){constUnsignedquotient=magnitude/10000;chunks[count++]=unsigned(magnitude-quotient*10000);magnitude=quotient;}if(_capture==nullptr&&_position>buffer_size-64)flush();charcaptured[64];char*constbegin=_capture!=nullptr?captured:_buffer+_position;char*destination=begin;constunsignedleading=unsigned(magnitude);constchar*first=digit_quads.data()+4*leading;intskip=leading<10?3:leading<100?2:leading<1000?1:0;for(;skip<4;skip++)*destination++=first[skip];while(count--){constchar*digits=digit_quads.data()+4*chunks[count];std::memcpy(destination,digits,4);destination+=4;}if(_capture!=nullptr){_capture->append(begin,destination-begin);}else{_position+=int(destination-begin);}}template<classT>std::enable_if_t<internal::has_val_method_v<T>&&!internal::is_integral_v<T>&&!internal::is_range_v<T>>write(constT&value){write(value.val());}template<classFirst,classSecond>voidwrite(conststd::pair<First,Second>&value){write(value.first);write_char(' ');write(value.second);}template<classRange>std::enable_if_t<internal::is_range_v<Range>&&!internal::is_string_like_v<Range>>write(constRange&range){usingStoredValue=internal::range_stored_value_t<constRange>;constexprboolnested=internal::is_range_v<StoredValue>&&!internal::is_string_like_v<StoredValue>;boolfirst=true;for(constauto&value:range){if(!first)write_char(nested?'\n':_range_separator);first=false;ifconstexpr(std::is_same_v<StoredValue,bool>&&!nested){write(static_cast<bool>(value));}else{write(value);}}}template<classFirst,class...Rest>voidprint(constFirst&first,constRest&...rest){write(first);((write_char(' '),write(rest)),...);}voidprintln(){write_char('\n');}voidset_precision(intprecision){_precision=precision;}voidset_fixed(intprecision=6){_float_format=std::chars_format::fixed;_precision=precision;}voidset_general(intprecision=6){_float_format=std::chars_format::general;_precision=precision;}voidset_range_separator(charseparator){_range_separator=separator;}template<classMatrix>voidwrite_aligned(constMatrix&matrix){usingRow=internal::range_stored_value_t<constMatrix>;usingCell=internal::range_stored_value_t<constRow>;static_assert(internal::is_range_v<Row>&&!internal::is_string_like_v<Row>,"write_aligned requires a two-dimensional range");static_assert(!internal::is_range_v<Cell>||internal::is_string_like_v<Cell>,"write_aligned requires scalar cells");write_aligned_matrix(matrix);}template<classMatrix>voidprintln_aligned(constMatrix&matrix){write_aligned(matrix);write_char('\n');}template<class...Args>voidprintln(constArgs&...args){print(args...);write_char('\n');}template<classT>FastOutput&operator<<(constT&value){write(value);return*this;}};}// namespace utilities}// namespace m1une#line 19 "verify/ds/persistent_cow.test.cpp"
#line 24 "verify/ds/persistent_cow.test.cpp"
namespace{usingAdd=m1une::monoid::Add<longlong>;usingRangeAdd=m1une::acted_monoid::RangeAddRangeSum<longlong>;structRangeAddBeats:RangeAdd{staticboolcan_apply(constoperator_type&,constvalue_type&){returntrue;}};template<classStructure,classUpdate,classGet>voidcheck_copy_move_and_reuse(Structurebase,Updateupdate,Getget){conststd::size_tbase_nodes=base.node_count();Structurecurrent=base;Structuresibling=current;update(current,0);assert(get(base)==0);assert(get(sibling)==0);assert(get(current)==1);update(sibling,9);assert(get(base)==0);assert(get(current)==1);assert(get(sibling)==10);conststd::size_tafter_first_write=current.node_count();update(current,1);assert(get(current)==2);assert(current.node_count()==after_first_write);Structuresnapshot=current;update(current,2);assert(get(snapshot)==2);assert(get(current)==3);conststd::size_tafter_reshare=current.node_count();update(current,3);assert(get(snapshot)==2);assert(get(current)==4);assert(current.node_count()==after_reshare);Structuremoved(std::move(current));update(moved,4);assert(get(moved)==5);Structureassigned=base;assigned=std::move(moved);update(assigned,5);assert(get(assigned)==6);assert(get(base)==0);sibling.release();snapshot.release();assigned.release();assert(base.node_count()==base_nodes);Structurereused=base;update(reused,6);assert(get(reused)==7);reused.release();assert(base.node_count()==base_nodes);}voidtest_segment_trees(){usingSeg=m1une::ds::PersistentSegtree<Add>;check_copy_move_and_reuse(Seg(std::vector<longlong>(8,0)),[](Seg&seg,intstep){seg.set_inplace(3,step+1);},[](constSeg&seg){returnseg.get(3);});usingLazy=m1une::ds::PersistentLazySegtree<RangeAdd>;check_copy_move_and_reuse(Lazy(std::vector<longlong>(8,0)),[](Lazy&seg,intstep){seg.set_inplace(3,RangeAdd::make(step+1));},[](constLazy&seg){returnseg.get(3).sum;});Lazybase(std::vector<longlong>(8,0));Lazycurrent=base;current.apply_inplace(0,8,10);conststd::size_tafter_full_cover=current.node_count();current.apply_inplace(0,8,1);assert(current.node_count()==after_full_cover);Lazysnapshot=current;current.apply_inplace(2,6,5);current.set_inplace(3,RangeAdd::make(100));assert(base.all_prod().sum==0);assert(snapshot.all_prod().sum==88);assert(snapshot.get(3).sum==11);assert(current.get(2).sum==16);assert(current.get(3).sum==100);Lazypersistent=base;Lazyinplace=base;std::uint64_tstate=1;for(intoperation=0;operation<500;++operation){state=state*6364136223846793005ULL+1;intleft=int(state%9);state=state*6364136223846793005ULL+1;intright=int(state%9);if(left>right)std::swap(left,right);longlongadd=static_cast<longlong>(operation%13)-6;persistent=persistent.apply(left,right,add);inplace.apply_inplace(left,right,add);if(operation%17==0){intindex=operation%8;autovalue=RangeAdd::make(operation);persistent=persistent.set(index,value);inplace.set_inplace(index,value);}autoinplace_values=inplace.to_vector();autopersistent_values=persistent.to_vector();assert(inplace_values.size()==persistent_values.size());for(inti=0;i<int(inplace_values.size());++i){assert(inplace_values[i].sum==persistent_values[i].sum);}}assert(base.all_prod().sum==0);usingDual=m1une::ds::PersistentDualSegtree<Add>;Dualdual_base(std::vector<longlong>(8,0));Dualdual=dual_base;dual.apply_inplace(1,7,4);dual.apply_inplace(3,6);dual.set_inplace(5,20);assert(dual_base.get(5)==0);assert(dual.get(3)==10);assert(dual.get(5)==20);usingBeats=m1une::ds::PersistentSegtreeBeats<RangeAddBeats>;Beatsbeats_base(std::vector<longlong>(8,0));Beatsbeats=beats_base;beats.apply_inplace(1,7,4);conststd::size_tbeats_nodes=beats.node_count();beats.apply_inplace(1,7,3);assert(beats.node_count()==beats_nodes);Beatsbeats_copy=beats;beats.set_inplace(3,RangeAddBeats::make(50));assert(beats_base.all_prod().sum==0);assert(beats_copy.get(3).sum==7);assert(beats.get(3).sum==50);}voidtest_dynamic_segment_trees(){usingSeg=m1une::ds::PersistentDynamicSegtree<Add>;Segbase(-100,100);Segcurrent=base;current.set_inplace(17,1);conststd::size_tnodes=current.node_count();current.set_inplace(17,2);assert(current.node_count()==nodes);Segcopy=current;current.set_inplace(17,3);assert(base.get(17)==0);assert(copy.get(17)==2);assert(current.get(17)==3);usingLazy=m1une::ds::PersistentDynamicLazySegtree<RangeAdd>;Lazylazy_base(-64,64,RangeAdd::make(0));Lazylazy=lazy_base;lazy.apply_inplace(-20,30,5);Lazylazy_copy=lazy;lazy.apply_inplace(-5,10,7);lazy.set_inplace(0,RangeAdd::make(100));assert(lazy_base.get(0).sum==0);assert(lazy_copy.get(0).sum==5);assert(lazy.get(-6).sum==5);assert(lazy.get(-5).sum==12);assert(lazy.get(0).sum==100);usingDual=m1une::ds::PersistentDynamicDualSegtree<Add>;Dualdual_base(-64,64,0);Dualdual=dual_base;dual.apply_inplace(-20,30,5);Dualdual_copy=dual;dual.apply_inplace(-5,10,7);dual.set_inplace(0,100);assert(dual_base.get(0)==0);assert(dual_copy.get(0)==5);assert(dual.get(-5)==12);assert(dual.get(0)==100);}voidtest_dynamic_arrays(){usingArray=m1une::ds::PersistentDynamicArray<int>;Arraybase={0,1,2,3,4,5};Arrayreversed=base.reverse(1,6);Arraycopy=reversed;reversed.set_inplace(1,20);conststd::size_tnodes=reversed.node_count();reversed.set_inplace(1,21);assert(reversed.node_count()==nodes);assert(base.to_vector()==(std::vector<int>{0,1,2,3,4,5}));assert(copy.to_vector()==(std::vector<int>{0,5,4,3,2,1}));assert(reversed.to_vector()==(std::vector<int>{0,21,4,3,2,1}));usingMonoidArray=m1une::ds::PersistentDynamicMonoidArray<Add>;MonoidArraymonoid(std::vector<longlong>{1,2,3,4});MonoidArraymonoid_copy=monoid;monoid.set_inplace(2,30);assert(monoid_copy.all_prod()==10);assert(monoid.all_prod()==37);usingLazyArray=m1une::ds::PersistentDynamicLazyMonoidArray<RangeAdd>;LazyArraylazy_base(std::vector<longlong>{1,2,3,4,5,6});LazyArraylazy=lazy_base.apply(1,6,10).reverse(0,5);LazyArraylazy_copy=lazy;lazy.apply_inplace(1,5,7);lazy.set_inplace(2,RangeAdd::make(100));assert(lazy_base.all_prod().sum==21);std::vector<longlong>copy_expected={15,14,13,12,1,16};autocopy_values=lazy_copy.to_vector();for(inti=0;i<int(copy_expected.size());++i){assert(copy_values[i].sum==copy_expected[i]);}std::vector<longlong>expected={15,21,100,19,8,16};autovalues=lazy.to_vector();for(inti=0;i<int(expected.size());++i)assert(values[i].sum==expected[i]);assert(lazy.all_prod().sum==179);}voidtest_dsu(){m1une::ds::PersistentDsubase(8);autocurrent=base;assert(current.merge_inplace(0,1));conststd::size_tafter_merge=current.node_count();assert(!current.merge_inplace(0,1));assert(current.node_count()==after_merge);autocopy=current;assert(current.merge_inplace(1,2));assert(!base.same(0,1));assert(!copy.same(0,2));assert(current.same(0,2));usingPotentialDsu=m1une::ds::PersistentPotentializedDsu<Add>;PotentialDsupotential_base(8);PotentialDsupotential=potential_base;assert(potential.merge_inplace(0,1,3));PotentialDsupotential_copy=potential;assert(potential.merge_inplace(1,2,4));assert(!potential.merge_inplace(0,2,8));assert(potential.diff(0,2)==7);assert(!potential_base.same(0,1));assert(!potential_copy.same(0,2));}voidtest_ordered_multiset(){usingMultiset=m1une::ds::PersistentOrderedMultiset<int>;Multisetbase={1,2,2,3};Multisetcurrent=base;current.insert_inplace(2,3);conststd::size_tafter_first_write=current.node_count();current.insert_inplace(2);assert(current.node_count()==after_first_write);Multisetcopy=current;assert(current.erase_inplace(2));assert(base.count(2)==2);assert(copy.count(2)==6);assert(current.count(2)==5);current.insert_inplace(4);assert(!base.contains(4));assert(current.contains(4));assert(current.erase_all_inplace(4));assert(!current.contains(4));assert(!current.erase_inplace(9));}}// namespaceintmain(){test_segment_trees();test_dynamic_segment_trees();test_dynamic_arrays();test_dsu();test_ordered_multiset();m1une::utilities::FastInputinput;m1une::utilities::FastOutputoutput;longlonga,b;input>>a>>b;output<<a+b<<'\n';}