珂朵莉树一定是世界上最幸福的数据结构——珂学进阶

· · 个人记录

前言

突然心血来潮想写写对珂学的理解,毕竟可快忘完了,头几天写P2486 [SDOI2011] 染色的时候我\texttt{ODT}还差点写挂。

正文

珂朵莉树,也叫\texttt{Old Driver Tree(ODT)},可以实现区间推平操作和区间查询操作,网上练习珂朵莉树的题是真的不多,毕竟本来就是去骗分的数据结构(功能鸡肋却强大,代码暴力却好写)。

[这篇珂朵莉树其实讲得挺好的](https://www.luogu.com.cn/blog/ACdreamer/chtholly-tree)。 主要的Code就是这几个操作 ```cpp struct node { int l,r; mutable int v; node(int l,int r=0,int v=0) :l(l),r(r),v(v) {} bool operator<(const node &a) const { return l<a.l; } }; set<node> s; set<node>::iterator split(int pos) { set<node>::iterator it=s.lower_bound(node(pos)); if(it!=s.end()&&it->l==pos) return it; it--; if(it->r<pos)return s.end(); int l=it->l; int r=it->r; int v=it->v; s.erase(it); s.insert(node(l,pos-1,v)); return s.insert(node(pos,r,v)).first; } inline void assign(int l,int r,int v) { set<node>::iterator itr=split(r+1),itl=split(l); s.erase(itl,itr); s.insert(node(l,r,v)); } inline int query(int l,int r) { int ans=0; set<node>::iterator itr=split(r+1),itl=split(l); int cc=-1; for(set<node>::iterator it=itl; it!=itr; it++) { int L=it->l; int R=it->r; if(cc!=it->v) ans++; cc=it->v; } return ans; } ``` ### 进阶 [P2486 [SDOI2011] 染色](https://www.luogu.com.cn/problem/P2486) 第一眼想到的就是树剖套珂朵莉树。。。 大概思路先把这个树以重链剖分一下,得到每个点的$\texttt{DFS}$序后就在序上去实现珂朵莉的区间推平和查询。 [我的珂朵莉总用时3.34s](https://www.luogu.com.cn/record/128716630) 细节上必须注意的是这两个函数(学过树剖求LCA的都应该看得懂吧)。 ```cpp inline int query2(int l,int r) { int ans=0; while(top[l]!=top[r]) { if(dep[top[l]]<dep[top[r]])Swap(l,r); ans+=query(ide[top[l]],ide[l]); if(query1(ide[top[l]],ide[top[l]])==query1(ide[fa[top[l]]],ide[fa[top[l]]]))ans--; l=fa[top[l]]; } if(dep[l]>dep[r])Swap(l,r); ans+=query(ide[l],ide[r]); return ans; } inline void update2(int l,int r,int c) { while(top[l]!=top[r]) { if(dep[top[l]]<dep[top[r]])Swap(l,r); assign(ide[top[l]],ide[l],c); l=fa[top[l]]; } if(dep[l]>dep[r])Swap(l,r); assign(ide[l],ide[r],c); } ``` [CF的一个题](https://codeforces.com/contest/1638/problem/E) 嗯,线段树套珂朵莉树。 操作$1$是珂朵莉,操作$2$是线段树。 单点查询 在树上维护一个$\texttt{lazytag}$就好了捏 [LCP 52. 二叉搜索树染色](https://leetcode.cn/problems/QO5KpG/) 看起来要树剖(是我太菜了吗),其实就是珂朵莉的板子嘛。。。 [P5251 [LnOI2019] 第二代图灵机](https://www.luogu.com.cn/problem/P5251) 也是一个线段树套珂朵莉树。 首先看到题目是有区间推平操作,并且 **你需要为第二代图灵机编写算法,使他能通过所有的图灵试验。为保证试验的正确性,所有数据都是随机生成的。** 啊,提醒的很明显,要珂朵莉,但是还有一个问题,就是怎样快速维护每个位置上的数字信息,毕竟你统计答案的时候是要用到的。 其实不需要Splay或者Treap,只要用线段树维护区间就好了鸭。 *** 做完这几个题你的柯学就差不多大毕业了。快去冲珂朵莉吧!