#line 1 "verify/ds/persistent_release.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/persistent_unionfind"
#line 1 "ds/bst/persistent_ordered_multiset.hpp"
#include<cassert>
#include<cstddef>
#include<functional>
#include<initializer_list>
#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/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/bst/persistent_ordered_set.hpp"
#line 9 "ds/bst/persistent_ordered_set.hpp"
#line 11 "ds/bst/persistent_ordered_set.hpp"
namespacem1une{namespaceds{template<typenameT,typenameCompare=std::less<T>>structPersistentOrderedSet{private:usingMultiset=PersistentOrderedMultiset<T,Compare>;Multisetdata;explicitPersistentOrderedSet(Multisetmultiset):data(std::move(multiset)){}public:explicitPersistentOrderedSet(Comparecompare):data(std::move(compare)){}PersistentOrderedSet():PersistentOrderedSet(Compare()){}PersistentOrderedSet(std::initializer_list<T>init,Comparecompare=Compare()):PersistentOrderedSet(std::move(compare)){for(constT&x:init)*this=insert(x);}template<typenameIterator>PersistentOrderedSet(Iteratorfirst,Iteratorlast,Comparecompare=Compare()):PersistentOrderedSet(std::move(compare)){while(first!=last){*this=insert(*first);++first;}}intsize()const{returndata.size();}intunique_size()const{returndata.size();}boolempty()const{returndata.empty();}voidrelease(){data.release();}std::size_tnode_count()const{returndata.node_count();}PersistentOrderedSetclear()const{returnPersistentOrderedSet(data.clear());}PersistentOrderedSetinsert(Tkey)const{returnPersistentOrderedSet(data.insert_unique(std::move(key)));}PersistentOrderedSeterase(constT&key)const{returnPersistentOrderedSet(data.erase(key));}boolcontains(constT&key)const{returndata.contains(key);}intcount(constT&key)const{returncontains(key)?1:0;}constT*find_by_order(intk)const{returndata.find_by_order(k);}Tkth(intk)const{returndata.kth(k);}intorder_of_key(constT&key)const{returndata.order_of_key(key);}intcount_less(constT&key)const{returndata.count_less(key);}intcount_less_equal(constT&key)const{returndata.count_less_equal(key);}intcount_greater(constT&key)const{returndata.count_greater(key);}intcount_greater_equal(constT&key)const{returndata.count_greater_equal(key);}constT*lower_bound(constT&key)const{returndata.lower_bound(key);}constT*upper_bound(constT&key)const{returndata.upper_bound(key);}constT*min_ge(constT&key)const{returndata.min_ge(key);}constT*min_gt(constT&key)const{returndata.min_gt(key);}constT*max_le(constT&key)const{returndata.max_le(key);}constT*max_lt(constT&key)const{returndata.max_lt(key);}constT*min()const{returndata.min();}constT*max()const{returndata.max();}std::pair<PersistentOrderedSet,PersistentOrderedSet>split(constT&key)const{auto[l,r]=data.split(key);return{PersistentOrderedSet(std::move(l)),PersistentOrderedSet(std::move(r))};}PersistentOrderedSetmerge(constPersistentOrderedSet&other)const{returnPersistentOrderedSet(data.merge(other.data));}std::vector<T>to_vector()const{returndata.to_vector();}};}// namespace ds}// namespace m1une#line 1 "ds/deque/persistent_deque.hpp"
#line 6 "ds/deque/persistent_deque.hpp"
#include<cstdint>
#line 8 "ds/deque/persistent_deque.hpp"
#include<memory>
#line 12 "ds/deque/persistent_deque.hpp"
namespacem1une{namespaceds{// Okasaki's purely persistent real-time deque.template<classT>structPersistentDeque{private:staticconstexprintbalance_factor=2;enumclassStreamKind:std::uint8_t{cons,take,rotate_drop,rotate_reverse,};// The three integer fields contain either an evaluated cons cell or the// arguments of one incremental stream operation.structStreamNode{mutableStreamKindkind;mutableintfirst;mutableintsecond;mutableintthird;StreamNode(StreamKindnode_kind,intfirst_argument,intsecond_argument,intthird_argument=-1):kind(node_kind),first(first_argument),second(second_argument),third(third_argument){}};structPool{std::deque<std::optional<T>>values;std::deque<std::optional<StreamNode>>streams;std::vector<int>value_references,stream_references;std::vector<int>next_free_value,next_free_stream;std::vector<int>unowned_values,unowned_streams;intfirst_free_value=-1;intfirst_free_stream=-1;std::size_tlive_values=0;std::size_tlive_streams=0;voidretain_value(intvalue){if(value!=-1)++value_references[value];}voidrelease_value(intvalue){if(value==-1)return;assert(values[value].has_value()&&value_references[value]>0);if(--value_references[value]!=0)return;values[value].reset();next_free_value[value]=first_free_value;first_free_value=value;--live_values;}voidretain_stream(intstream){if(stream!=-1)++stream_references[stream];}voidretain_dependencies(constStreamNode&node){if(node.kind==StreamKind::cons){retain_value(node.first);retain_stream(node.second);}elseif(node.kind==StreamKind::take){retain_stream(node.first);}elseif(node.kind==StreamKind::rotate_drop){retain_stream(node.first);retain_stream(node.third);}else{retain_stream(node.first);retain_stream(node.second);retain_stream(node.third);}}voidrelease_zero_stream(intstream){std::vector<int>pending={stream};while(!pending.empty()){intcurrent=pending.back();pending.pop_back();assert(streams[current].has_value()&&stream_references[current]==0);StreamNodenode=*streams[current];streams[current].reset();next_free_stream[current]=first_free_stream;first_free_stream=current;--live_streams;autorelease_child=[&](intchild){if(child!=-1&&--stream_references[child]==0)pending.push_back(child);};if(node.kind==StreamKind::cons){release_value(node.first);release_child(node.second);}elseif(node.kind==StreamKind::take){release_child(node.first);}elseif(node.kind==StreamKind::rotate_drop){release_child(node.first);release_child(node.third);}else{release_child(node.first);release_child(node.second);release_child(node.third);}}}voidrelease_stream(intstream){if(stream==-1)return;assert(streams[stream].has_value()&&stream_references[stream]>0);if(--stream_references[stream]==0)release_zero_stream(stream);}template<class...Args>intstore_value(Args&&...args){intresult;if(first_free_value==-1){result=int(values.size());values.emplace_back(std::in_place,std::forward<Args>(args)...);value_references.push_back(0);next_free_value.push_back(-1);}else{result=first_free_value;first_free_value=next_free_value[result];values[result].emplace(std::forward<Args>(args)...);value_references[result]=0;}unowned_values.push_back(result);++live_values;returnresult;}intmake_stream(StreamKindkind,intfirst,intsecond,intthird){intresult;if(first_free_stream==-1){result=int(streams.size());streams.emplace_back(std::in_place,kind,first,second,third);stream_references.push_back(0);next_free_stream.push_back(-1);}else{result=first_free_stream;first_free_stream=next_free_stream[result];streams[result].emplace(kind,first,second,third);stream_references[result]=0;}retain_dependencies(*streams[result]);unowned_streams.push_back(result);++live_streams;returnresult;}voidset_cons(intstream,intvalue,inttail){retain_value(value);retain_stream(tail);StreamNodeold=*streams[stream];if(old.kind==StreamKind::take){release_stream(old.first);}elseif(old.kind==StreamKind::rotate_drop){release_stream(old.first);release_stream(old.third);}elseif(old.kind==StreamKind::rotate_reverse){release_stream(old.first);release_stream(old.second);release_stream(old.third);}else{release_value(old.first);release_stream(old.second);}StreamNode&node=*streams[stream];node.kind=StreamKind::cons;node.first=value;node.second=tail;node.third=-1;}voiddiscard_unreferenced(){while(!unowned_streams.empty()){intstream=unowned_streams.back();unowned_streams.pop_back();if(streams[stream].has_value()&&stream_references[stream]==0)release_zero_stream(stream);}while(!unowned_values.empty()){intvalue=unowned_values.back();unowned_values.pop_back();if(values[value].has_value()&&value_references[value]==0){values[value].reset();next_free_value[value]=first_free_value;first_free_value=value;--live_values;}}}std::size_tsize()const{returnlive_values+live_streams;}};int_front_size;int_front;int_front_schedule;int_rear_size;int_rear;int_rear_schedule;std::shared_ptr<Pool>_pool;PersistentDeque(intfront_size,intfront,intfront_schedule,intrear_size,intrear,intrear_schedule,std::shared_ptr<Pool>pool):_front_size(front_size),_front(front),_front_schedule(front_schedule),_rear_size(rear_size),_rear(rear),_rear_schedule(rear_schedule),_pool(std::move(pool)){retain_state();_pool->discard_unreferenced();}voidretain_state()const{_pool->retain_stream(_front);_pool->retain_stream(_front_schedule);_pool->retain_stream(_rear);_pool->retain_stream(_rear_schedule);}voidrelease_state()const{_pool->release_stream(_front);_pool->release_stream(_front_schedule);_pool->release_stream(_rear);_pool->release_stream(_rear_schedule);}template<class...Args>intstore_value(Args&&...args)const{return_pool->store_value(std::forward<Args>(args)...);}intmake_stream(StreamKindkind,intfirst,intsecond,intthird=-1)const{return_pool->make_stream(kind,first,second,third);}intmake_cons(intvalue_index,inttail)const{returnmake_stream(StreamKind::cons,value_index,tail);}intmake_take(intcount,intstream)const{if(count==0)return-1;assert(count>0&&stream!=-1);returnmake_stream(StreamKind::take,stream,count);}intmake_rotate_drop(intrear,intcount,intfront)const{returnmake_stream(StreamKind::rotate_drop,rear,count,front);}intmake_rotate_reverse(intrear,intfront,intaccumulator)const{returnmake_stream(StreamKind::rotate_reverse,rear,front,accumulator);}voidset_cons(intstream,intvalue_index,inttail)const{_pool->set_cons(stream,value_index,tail);}intstream_head(intstream)const{assert(stream!=-1);force(stream);return(*_pool->streams[stream]).first;}intstream_tail(intstream)const{assert(stream!=-1);force(stream);return(*_pool->streams[stream]).second;}intdrop(intstream,intcount)const{assert(count>=0);while(count>0){assert(stream!=-1);stream=stream_tail(stream);count--;}returnstream;}// Reverses a bounded prefix onto accumulator and returns the unconsumed// suffix together with the new accumulator.std::pair<int,int>reverse_prefix(intstream,intcount,intaccumulator)const{while(count>0&&stream!=-1){intvalue_index=stream_head(stream);stream=stream_tail(stream);accumulator=make_cons(value_index,accumulator);count--;}return{stream,accumulator};}voidforce(intstream)const{assert(stream!=-1);StreamNodenode=*_pool->streams[stream];if(node.kind==StreamKind::cons)return;if(node.kind==StreamKind::take){intsource=node.first;intcount=node.second;assert(source!=-1&&count>0);intvalue_index=stream_head(source);inttail=make_take(count-1,stream_tail(source));set_cons(stream,value_index,tail);return;}if(node.kind==StreamKind::rotate_drop){intrear=node.first;intcount=node.second;intfront=node.third;if(count<balance_factor||rear==-1){assert(count<=balance_factor||rear!=-1);intresult=make_rotate_reverse(rear,drop(front,count),-1);set_cons(stream,stream_head(result),stream_tail(result));return;}assert(rear!=-1);intvalue_index=stream_head(rear);inttail=make_rotate_drop(stream_tail(rear),count-balance_factor,drop(front,balance_factor));set_cons(stream,value_index,tail);return;}assert(node.kind==StreamKind::rotate_reverse);intrear=node.first;intfront=node.second;intaccumulator=node.third;if(rear==-1){auto[remaining,result]=reverse_prefix(front,balance_factor+1,accumulator);assert(remaining==-1&&result!=-1);set_cons(stream,stream_head(result),stream_tail(result));return;}intvalue_index=stream_head(rear);auto[remaining,next_accumulator]=reverse_prefix(front,balance_factor,accumulator);inttail=make_rotate_reverse(stream_tail(rear),remaining,next_accumulator);set_cons(stream,value_index,tail);}intexecute_once(intschedule)const{returnschedule==-1?-1:stream_tail(schedule);}intexecute_twice(intschedule)const{returnexecute_once(execute_once(schedule));}PersistentDequecheck(intfront_size,intfront,intfront_schedule,intrear_size,intrear,intrear_schedule)const{if(front_size>balance_factor*rear_size+1){intnext_front_size=(front_size+rear_size)/2;intnext_rear_size=front_size+rear_size-next_front_size;intnext_front=make_take(next_front_size,front);intnext_rear=make_rotate_drop(rear,next_front_size,front);returnPersistentDeque(next_front_size,next_front,next_front,next_rear_size,next_rear,next_rear,_pool);}if(rear_size>balance_factor*front_size+1){intnext_front_size=(front_size+rear_size)/2;intnext_rear_size=front_size+rear_size-next_front_size;intnext_front=make_rotate_drop(front,next_rear_size,rear);intnext_rear=make_take(next_rear_size,rear);returnPersistentDeque(next_front_size,next_front,next_front,next_rear_size,next_rear,next_rear,_pool);}returnPersistentDeque(front_size,front,front_schedule,rear_size,rear,rear_schedule,_pool);}public:PersistentDeque():_front_size(0),_front(-1),_front_schedule(-1),_rear_size(0),_rear(-1),_rear_schedule(-1),_pool(std::make_shared<Pool>()){}PersistentDeque(constPersistentDeque&other):_front_size(other._front_size),_front(other._front),_front_schedule(other._front_schedule),_rear_size(other._rear_size),_rear(other._rear),_rear_schedule(other._rear_schedule),_pool(other._pool){if(_pool)retain_state();}PersistentDeque(PersistentDeque&&other)noexcept:_front_size(other._front_size),_front(other._front),_front_schedule(other._front_schedule),_rear_size(other._rear_size),_rear(other._rear),_rear_schedule(other._rear_schedule),_pool(std::move(other._pool)){other._front_size=other._rear_size=0;other._front=other._front_schedule=other._rear=other._rear_schedule=-1;}PersistentDeque&operator=(constPersistentDeque&other){if(this==&other)return*this;if(other._pool)other.retain_state();if(_pool)release_state();_front_size=other._front_size;_front=other._front;_front_schedule=other._front_schedule;_rear_size=other._rear_size;_rear=other._rear;_rear_schedule=other._rear_schedule;_pool=other._pool;return*this;}PersistentDeque&operator=(PersistentDeque&&other)noexcept{if(this==&other)return*this;if(_pool)release_state();_front_size=other._front_size;_front=other._front;_front_schedule=other._front_schedule;_rear_size=other._rear_size;_rear=other._rear;_rear_schedule=other._rear_schedule;_pool=std::move(other._pool);other._front_size=other._rear_size=0;other._front=other._front_schedule=other._rear=other._rear_schedule=-1;return*this;}~PersistentDeque(){if(_pool)release_state();}intsize()const{return_front_size+_rear_size;}boolempty()const{returnsize()==0;}voidrelease(){if(_pool)release_state();_front_size=_rear_size=0;_front=_front_schedule=_rear=_rear_schedule=-1;_pool=std::make_shared<Pool>();}std::size_tnode_count()const{return_pool?_pool->size():0;}constT&front()const{assert(!empty());intstream=_front==-1?_rear:_front;intvalue=stream_head(stream);_pool->discard_unreferenced();return*_pool->values[value];}constT&back()const{assert(!empty());intstream=_rear==-1?_front:_rear;intvalue=stream_head(stream);_pool->discard_unreferenced();return*_pool->values[value];}PersistentDequepush_front(Tvalue)const{returnemplace_front(std::move(value));}template<class...Args>PersistentDequeemplace_front(Args&&...args)const{intvalue_index=store_value(std::forward<Args>(args)...);returncheck(_front_size+1,make_cons(value_index,_front),execute_once(_front_schedule),_rear_size,_rear,execute_once(_rear_schedule));}PersistentDequepush_back(Tvalue)const{returnemplace_back(std::move(value));}template<class...Args>PersistentDequeemplace_back(Args&&...args)const{intvalue_index=store_value(std::forward<Args>(args)...);returncheck(_front_size,_front,execute_once(_front_schedule),_rear_size+1,make_cons(value_index,_rear),execute_once(_rear_schedule));}PersistentDequepop_front()const{assert(!empty());if(size()==1)returnclear();assert(_front!=-1);returncheck(_front_size-1,stream_tail(_front),execute_twice(_front_schedule),_rear_size,_rear,execute_twice(_rear_schedule));}PersistentDequepop_back()const{assert(!empty());if(size()==1)returnclear();assert(_rear!=-1);returncheck(_front_size,_front,execute_twice(_front_schedule),_rear_size-1,stream_tail(_rear),execute_twice(_rear_schedule));}PersistentDequeclear()const{returnPersistentDeque(0,-1,-1,0,-1,-1,_pool);}};}// namespace ds}// namespace m1une#line 1 "ds/dsu/partially_persistent_dsu.hpp"
#include<algorithm>
#line 9 "ds/dsu/partially_persistent_dsu.hpp"
namespacem1une{namespaceds{structPartiallyPersistentDsu{private:staticconstexprintnever=std::numeric_limits<int>::max();int_n;int_time;std::vector<int>parent;std::vector<int>parent_time;std::vector<std::vector<std::pair<int,int>>>size_history;staticintcheck_size(intn){assert(0<=n);returnn;}voidcheck_time(intt)const{assert(0<=t&&t<=_time);}public:PartiallyPersistentDsu():PartiallyPersistentDsu(0){}explicitPartiallyPersistentDsu(intn):_n(check_size(n)),_time(0),parent(_n,-1),parent_time(_n,never),size_history(_n){for(inti=0;i<_n;i++)size_history[i].emplace_back(0,1);}intsize()const{return_n;}boolempty()const{return_n==0;}// Releases the complete history and resets this object to an empty DSU.voidrelease(){_n=0;_time=0;std::vector<int>().swap(parent);std::vector<int>().swap(parent_time);std::vector<std::vector<std::pair<int,int>>>().swap(size_history);}inttime()const{return_time;}intleader(intt,inta)const{check_time(t);assert(0<=a&&a<_n);while(parent_time[a]<=t)a=parent[a];returna;}intleader(inta)const{returnleader(_time,a);}boolsame(intt,inta,intb)const{check_time(t);assert(0<=a&&a<_n);assert(0<=b&&b<_n);returnleader(t,a)==leader(t,b);}boolsame(inta,intb)const{returnsame(_time,a,b);}intgroup_size(intt,inta)const{intr=leader(t,a);constauto&h=size_history[r];autoit=std::upper_bound(h.begin(),h.end(),std::pair<int,int>(t,never));--it;returnit->second;}intgroup_size(inta)const{return-parent[leader(a)];}intsize(intt,inta)const{returngroup_size(t,a);}intsize(inta)const{returngroup_size(a);}boolmerge(inta,intb){assert(0<=a&&a<_n);assert(0<=b&&b<_n);++_time;intx=leader(a),y=leader(b);if(x==y)returnfalse;if(-parent[x]<-parent[y]){std::swap(x,y);}parent[x]+=parent[y];parent[y]=x;parent_time[y]=_time;size_history[x].emplace_back(_time,-parent[x]);returntrue;}std::vector<std::vector<int>>groups(intt)const{check_time(t);std::vector<int>leader_buf(_n),group_size(_n);for(inti=0;i<_n;i++){leader_buf[i]=leader(t,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;}std::vector<std::vector<int>>groups()const{returngroups(_time);}};}// namespace ds}// namespace m1une#line 1 "ds/dsu/persistent_dsu.hpp"
#line 10 "ds/dsu/persistent_dsu.hpp"
#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/dynamic_array/persistent_dynamic_array.hpp"
#line 5 "ds/dynamic_array/persistent_dynamic_array.hpp"
#include<chrono>
#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/queue/persistent_queue.hpp"
#line 11 "ds/queue/persistent_queue.hpp"
namespacem1une{namespaceds{// Purely persistent FIFO queue with worst-case O(1) operations.template<classT>structPersistentQueue{private:structLink{intvalue_index;intnext;Link(intindex,intnext_link):value_index(index),next(next_link){}};structPool{std::deque<std::optional<T>>values;std::deque<std::optional<Link>>links;std::vector<int>value_references,link_references;std::vector<int>next_free_value,next_free_link;std::vector<int>unowned_values,unowned_links;intfirst_free_value=-1;intfirst_free_link=-1;std::size_tlive_values=0;std::size_tlive_links=0;voidretain_value(intvalue){if(value!=-1)++value_references[value];}voidrelease_value(intvalue){if(value==-1)return;assert(values[value].has_value()&&value_references[value]>0);if(--value_references[value]!=0)return;values[value].reset();next_free_value[value]=first_free_value;first_free_value=value;--live_values;}voidretain_link(intlink){if(link!=-1)++link_references[link];}voidrelease_zero_link(intlink){while(link!=-1){assert(links[link].has_value()&&link_references[link]==0);intvalue=links[link]->value_index;intnext=links[link]->next;links[link].reset();next_free_link[link]=first_free_link;first_free_link=link;--live_links;release_value(value);if(next==-1||--link_references[next]!=0)return;link=next;}}voidrelease_link(intlink){if(link==-1)return;assert(links[link].has_value()&&link_references[link]>0);if(--link_references[link]==0)release_zero_link(link);}intstore_value(Tvalue){intresult;if(first_free_value==-1){result=int(values.size());values.emplace_back(std::in_place,std::move(value));value_references.push_back(0);next_free_value.push_back(-1);}else{result=first_free_value;first_free_value=next_free_value[result];values[result].emplace(std::move(value));value_references[result]=0;}unowned_values.push_back(result);++live_values;returnresult;}intmake_link(intvalue,intnext){intresult;if(first_free_link==-1){result=int(links.size());links.emplace_back(std::in_place,value,next);link_references.push_back(0);next_free_link.push_back(-1);}else{result=first_free_link;first_free_link=next_free_link[result];links[result].emplace(value,next);link_references[result]=0;}retain_value(value);retain_link(next);unowned_links.push_back(result);++live_links;returnresult;}voiddiscard_unreferenced(){while(!unowned_links.empty()){intlink=unowned_links.back();unowned_links.pop_back();if(links[link].has_value()&&link_references[link]==0)release_zero_link(link);}while(!unowned_values.empty()){intvalue=unowned_values.back();unowned_values.pop_back();if(values[value].has_value()&&value_references[value]==0){values[value].reset();next_free_value[value]=first_free_value;first_free_value=value;--live_values;}}}std::size_tsize()const{returnlive_values+live_links;}};enumclassRotationPhase{idle,reversing,appending,done,};structRotationState{RotationPhasephase=RotationPhase::idle;intvalid_count=0;intremaining_front=-1;intreversed_front=-1;intremaining_rear=-1;intreversed_rear=-1;};int_front_size;int_front;RotationState_rotation;int_rear_size;int_rear;int_back_value;std::shared_ptr<Pool>_pool;PersistentQueue(intfront_size,intfront,RotationStaterotation,intrear_size,intrear,intback_value,std::shared_ptr<Pool>pool):_front_size(front_size),_front(front),_rotation(rotation),_rear_size(rear_size),_rear(rear),_back_value(back_value),_pool(std::move(pool)){retain_state();_pool->discard_unreferenced();}voidretain_state()const{_pool->retain_link(_front);_pool->retain_link(_rotation.remaining_front);_pool->retain_link(_rotation.reversed_front);_pool->retain_link(_rotation.remaining_rear);_pool->retain_link(_rotation.reversed_rear);_pool->retain_link(_rear);_pool->retain_value(_back_value);}voidrelease_state()const{_pool->release_link(_front);_pool->release_link(_rotation.remaining_front);_pool->release_link(_rotation.reversed_front);_pool->release_link(_rotation.remaining_rear);_pool->release_link(_rotation.reversed_rear);_pool->release_link(_rear);_pool->release_value(_back_value);}intnext_link(intlink)const{assert(link!=-1);return(*_pool->links[link]).next;}intlink_value(intlink)const{assert(link!=-1);return(*_pool->links[link]).value_index;}intmake_link(intvalue_index,intnext)const{return_pool->make_link(value_index,next);}intstore_value(Tvalue)const{return_pool->store_value(std::move(value));}RotationStateexecute(RotationStatestate)const{if(state.phase==RotationPhase::reversing){assert(state.remaining_rear!=-1);if(state.remaining_front!=-1){state.reversed_front=make_link(link_value(state.remaining_front),state.reversed_front);state.remaining_front=next_link(state.remaining_front);state.reversed_rear=make_link(link_value(state.remaining_rear),state.reversed_rear);state.remaining_rear=next_link(state.remaining_rear);state.valid_count++;}else{assert(next_link(state.remaining_rear)==-1);state.reversed_rear=make_link(link_value(state.remaining_rear),state.reversed_rear);state.remaining_rear=-1;state.phase=RotationPhase::appending;}}elseif(state.phase==RotationPhase::appending){assert(state.valid_count>=0);if(state.valid_count==0){state.phase=RotationPhase::done;}else{assert(state.reversed_front!=-1);state.reversed_rear=make_link(link_value(state.reversed_front),state.reversed_rear);state.reversed_front=next_link(state.reversed_front);state.valid_count--;}}returnstate;}RotationStateinvalidate(RotationStatestate)const{if(state.phase==RotationPhase::reversing){state.valid_count--;}elseif(state.phase==RotationPhase::appending){if(state.valid_count==0){assert(state.reversed_rear!=-1);state.reversed_rear=next_link(state.reversed_rear);state.phase=RotationPhase::done;}else{state.valid_count--;}}returnstate;}PersistentQueueexecute_twice(intfront_size,intfront,RotationStaterotation,intrear_size,intrear,intback_value)const{rotation=execute(std::move(rotation));rotation=execute(std::move(rotation));if(rotation.phase==RotationPhase::done){front=rotation.reversed_rear;rotation=RotationState();}returnPersistentQueue(front_size,front,rotation,rear_size,rear,back_value,_pool);}PersistentQueuecheck(intfront_size,intfront,RotationStaterotation,intrear_size,intrear,intback_value)const{if(rear_size<=front_size){returnexecute_twice(front_size,front,rotation,rear_size,rear,back_value);}RotationStatenext_rotation;next_rotation.phase=RotationPhase::reversing;next_rotation.remaining_front=front;next_rotation.remaining_rear=rear;returnexecute_twice(front_size+rear_size,front,next_rotation,0,-1,back_value);}public:PersistentQueue():_front_size(0),_front(-1),_rear_size(0),_rear(-1),_back_value(-1),_pool(std::make_shared<Pool>()){}PersistentQueue(constPersistentQueue&other):_front_size(other._front_size),_front(other._front),_rotation(other._rotation),_rear_size(other._rear_size),_rear(other._rear),_back_value(other._back_value),_pool(other._pool){if(_pool)retain_state();}PersistentQueue(PersistentQueue&&other)noexcept:_front_size(other._front_size),_front(other._front),_rotation(other._rotation),_rear_size(other._rear_size),_rear(other._rear),_back_value(other._back_value),_pool(std::move(other._pool)){other._front_size=other._rear_size=0;other._front=other._rear=other._back_value=-1;other._rotation=RotationState();}PersistentQueue&operator=(constPersistentQueue&other){if(this==&other)return*this;if(other._pool)other.retain_state();if(_pool)release_state();_front_size=other._front_size;_front=other._front;_rotation=other._rotation;_rear_size=other._rear_size;_rear=other._rear;_back_value=other._back_value;_pool=other._pool;return*this;}PersistentQueue&operator=(PersistentQueue&&other)noexcept{if(this==&other)return*this;if(_pool)release_state();_front_size=other._front_size;_front=other._front;_rotation=other._rotation;_rear_size=other._rear_size;_rear=other._rear;_back_value=other._back_value;_pool=std::move(other._pool);other._front_size=other._rear_size=0;other._front=other._rear=other._back_value=-1;other._rotation=RotationState();return*this;}~PersistentQueue(){if(_pool)release_state();}intsize()const{return_front_size+_rear_size;}boolempty()const{returnsize()==0;}voidrelease(){if(_pool)release_state();_front_size=_rear_size=0;_front=_rear=_back_value=-1;_rotation=RotationState();_pool=std::make_shared<Pool>();}std::size_tnode_count()const{return_pool?_pool->size():0;}constT&front()const{assert(!empty()&&_front!=-1);return*_pool->values[link_value(_front)];}constT&back()const{assert(!empty()&&_back_value!=-1);return*_pool->values[_back_value];}PersistentQueuepush(Tvalue)const{intvalue_index=store_value(std::move(value));intrear=make_link(value_index,_rear);returncheck(_front_size,_front,_rotation,_rear_size+1,rear,value_index);}PersistentQueuepush_back(Tvalue)const{returnpush(std::move(value));}PersistentQueuepop()const{assert(!empty()&&_front!=-1);intback_value=size()==1?-1:_back_value;returncheck(_front_size-1,next_link(_front),invalidate(_rotation),_rear_size,_rear,back_value);}PersistentQueuepop_front()const{returnpop();}PersistentQueueclear()const{returnPersistentQueue(0,-1,RotationState(),0,-1,-1,_pool);}};}// namespace ds}// namespace m1une#line 1 "ds/stack/persistent_stack.hpp"
#line 11 "ds/stack/persistent_stack.hpp"
namespacem1une{namespaceds{// Purely persistent LIFO stack with O(1) operations.template<classT>structPersistentStack{private:structNode{Tvalue;intnext;template<class...Args>Node(intnext_node,Args&&...args):value(std::forward<Args>(args)...),next(next_node){}};structPool{std::deque<std::optional<Node>>nodes;std::vector<int>references;std::vector<int>next_free;intfirst_free=-1;std::size_tlive_nodes=0;template<class...Args>intemplace(intnext,Args&&...args){intresult;if(first_free==-1){result=int(nodes.size());nodes.emplace_back(std::in_place,next,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(next,std::forward<Args>(args)...);references[result]=0;}retain(next);++live_nodes;returnresult;}Node&operator[](intnode){return*nodes[node];}constNode&operator[](intnode)const{return*nodes[node];}voidretain(intnode){if(node!=-1)++references[node];}voidrelease(intnode){while(node!=-1){assert(nodes[node].has_value()&&references[node]>0);if(--references[node]!=0)return;intnext=nodes[node]->next;nodes[node].reset();next_free[node]=first_free;first_free=node;--live_nodes;node=next;}}};int_size;int_top;std::shared_ptr<Pool>_pool;PersistentStack(intstack_size,inttop,std::shared_ptr<Pool>pool):_size(stack_size),_top(top),_pool(std::move(pool)){_pool->retain(_top);}public:PersistentStack():_size(0),_top(-1),_pool(std::make_shared<Pool>()){}PersistentStack(constPersistentStack&other):_size(other._size),_top(other._top),_pool(other._pool){if(_pool)_pool->retain(_top);}PersistentStack(PersistentStack&&other)noexcept:_size(other._size),_top(other._top),_pool(std::move(other._pool)){other._size=0;other._top=-1;}PersistentStack&operator=(constPersistentStack&other){if(this==&other)return*this;if(other._pool)other._pool->retain(other._top);if(_pool)_pool->release(_top);_size=other._size;_top=other._top;_pool=other._pool;return*this;}PersistentStack&operator=(PersistentStack&&other)noexcept{if(this==&other)return*this;if(_pool)_pool->release(_top);_size=other._size;_top=other._top;_pool=std::move(other._pool);other._size=0;other._top=-1;return*this;}~PersistentStack(){if(_pool)_pool->release(_top);}intsize()const{return_size;}boolempty()const{return_size==0;}voidrelease(){if(_pool)_pool->release(_top);_size=0;_top=-1;_pool=std::make_shared<Pool>();}std::size_tnode_count()const{return_pool?_pool->live_nodes:0;}constT&top()const{assert(!empty()&&_top!=-1);return(*_pool)[_top].value;}PersistentStackpush(Tvalue)const{returnemplace(std::move(value));}template<class...Args>PersistentStackemplace(Args&&...args)const{inttop=_pool->emplace(_top,std::forward<Args>(args)...);returnPersistentStack(_size+1,top,_pool);}PersistentStackpop()const{assert(!empty()&&_top!=-1);returnPersistentStack(_size-1,(*_pool)[_top].next,_pool);}PersistentStackclear()const{returnPersistentStack(0,-1,_pool);}};}// namespace ds}// namespace m1une#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 "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>
#include<type_traits>
#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 17 "verify/ds/persistent_release.test.cpp"
#line 22 "verify/ds/persistent_release.test.cpp"
voidtest_release(){{m1une::ds::PersistentDynamicArray<int>base={1,2,3,4};autobranch=base.insert(2,9).reverse();std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live);std::vector<int>expected={1,2,3,4};assert(base.to_vector()==expected);base.release();assert(base.empty()&&base.node_count()==0);}{usingArray=m1une::ds::PersistentDynamicMonoidArray<m1une::monoid::Add<longlong>>;Arraybase(std::vector<longlong>{1,2,3});autobranch=base.set(1,7).reverse();std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live&&base.all_prod()==6);base.release();assert(base.empty()&&base.node_count()==0);}{usingActedMonoid=m1une::acted_monoid::RangeAddRangeSum<longlong>;usingArray=m1une::ds::PersistentDynamicLazyMonoidArray<ActedMonoid>;Arraybase(std::vector<longlong>{1,2,3});autobranch=base.apply(0,2,5).reverse();std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live&&base.all_prod().sum==6);base.release();assert(base.empty()&&base.node_count()==0);}{m1une::ds::PersistentDsubase(5);autobranch=base.merge(0,1).merge(1,2);std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live&&!base.same(0,1));base.release();assert(base.empty()&&base.node_count()==0);}{usingDsu=m1une::ds::PersistentPotentializedDsu<m1une::monoid::Add<longlong>>;Dsubase(4);autobranch=base.merge(0,1,3).first.merge(1,2,4).first;std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live&&!base.same(0,1));base.release();assert(base.empty()&&base.node_count()==0);}{m1une::ds::PersistentStack<int>base;base=base.push(1).push(2);autobranch=base.push(3);std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live&&base.top()==2);base.release();assert(base.empty()&&base.node_count()==0);}{m1une::ds::PersistentQueue<int>base;base=base.push(1).push(2).push(3);autobranch=base.push(4).pop();std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live);assert(base.front()==1&&base.back()==3);base.release();assert(base.empty()&&base.node_count()==0);}{m1une::ds::PersistentDeque<int>base;base=base.push_back(1).push_front(2).push_back(3);autobranch=base.push_front(4).pop_back();std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live);assert(base.front()==2&&base.back()==3);base.release();assert(base.empty()&&base.node_count()==0);}{m1une::ds::PersistentOrderedMultiset<int>base={1,2,3};autobranch=base.insert(4).erase(2);std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live&&base.contains(2));base.release();assert(base.empty()&&base.node_count()==0);}{m1une::ds::PersistentOrderedSet<int>base={1,2,3};autobranch=base.insert(4).erase(2);std::size_tlive=base.node_count();branch.release();assert(base.node_count()<live&&base.contains(2));base.release();assert(base.empty()&&base.node_count()==0);}{m1une::ds::PartiallyPersistentDsudsu(4);dsu.merge(0,1);dsu.merge(2,3);dsu.release();assert(dsu.empty()&&dsu.time()==0);}{autovalue=std::make_shared<int>(1);std::weak_ptr<int>lifetime=value;m1une::ds::PersistentDynamicArray<std::shared_ptr<int>>empty;autoversion=empty.push_back(value);value.reset();assert(!lifetime.expired());version.release();assert(lifetime.expired());}{autovalue=std::make_shared<int>(1);std::weak_ptr<int>lifetime=value;m1une::ds::PersistentStack<std::shared_ptr<int>>empty;autoversion=empty.push(value);value.reset();version.release();assert(lifetime.expired());}{autovalue=std::make_shared<int>(1);std::weak_ptr<int>lifetime=value;m1une::ds::PersistentQueue<std::shared_ptr<int>>empty;autoversion=empty.push(value);value.reset();version.release();assert(lifetime.expired());}{autovalue=std::make_shared<int>(1);std::weak_ptr<int>lifetime=value;m1une::ds::PersistentDeque<std::shared_ptr<int>>empty;autoversion=empty.push_back(value);value.reset();version.release();assert(lifetime.expired());}}intmain(){test_release();m1une::utilities::FastInputfast_input;m1une::utilities::FastOutputfast_output;intn,query_count;fast_input>>n>>query_count;usingDsu=m1une::ds::PersistentDsu;std::vector<Dsu>versions;versions.emplace_back(n);while(query_count--){inttype,version,u,v;fast_input>>type>>version>>u>>v;constDsu&base=versions[version+1];if(type==0){versions.push_back(base.merge(u,v));}else{fast_output<<int(base.same(u,v))<<'\n';versions.emplace_back();}}}