版本比较
数据结构——左偏树/可并堆学习笔记
正文
增加 16 行删除 16 行
16 行未改动171819202121222324259 行未改动35363738393940414243101 行未改动全部展开14514614714814914915015115115215315415598 行未改动25425525625725825826025926026126226226326426426526626726826927027027127227327414 行未改动2892902912922932932942952962976 行未改动304305306307308308309310311312110 行未改动全部展开4234244254264274274284294304318 行未改动44044144244344444444544644744855 行未改动50450550650750850951050850951051151251351439 行未改动16 行未改动
很显然,因为二叉堆($\texttt{priority\_queue}$)的性质很有限(重点只有一句话),所以它支持的操作也十分有限,常用的只有查询堆顶($\texttt{top}$),压入堆($\texttt{push}$),弹出堆顶($\texttt{pop}$)。
如果我们想要让两个堆合并,暴力的做法就需要 $O(n\log n)$ 的时间复杂度,显然这还不是最优解。那么为了应对合并的情况,可并堆就诞生了,它可以用 还不是最优解。那么为了应对合并的情况,可并堆就诞生了,它可以用$O(\log n + \log m)$ 的时间复杂度完美胜任合并两个堆的任务。下面,我就来介绍竞赛中常见的一种实现方法: $\textbf{左偏树}$
9 行未改动”
以上为引用。
$ \texttt{qk} $ 版定义: $ \texttt{qk} $ 版定义:
设当前结点为 $\texttt{p}$,则 $dist_p$ 为子树中深度最小的空结点的到 $\texttt{p}$ 的距离。
注:$\texttt{dist}$ 又称 $\texttt{npl}$ 或 $\texttt{s-value}$101 行未改动全部展开 for(int i = 1;i <= n;++ i) q.push(i); while(q.size() > 1){ int x = q.front();q.pop(); int y = q.front();q.pop(); q.push(merge(x, y));//取出前两个合并 q.push(merge(x, y));//取出前两个合并 } return q.front();//返回合并出的根结点 return q.front();//返回合并出的根结点}```
时间复杂度可以看这张图:98 行未改动
这种要求就十分好满足了,有两种情况。 - 删除的是根结点,和上文中的 $\textbf{pop函数}$ 一样,不再赘述。 - 删除的是某个结点的子结点,这时其实仍然可以通过合并左右儿子的方式来删除,但问题是,这样删除会影响到这个结点的祖先。所以我们对每个节点记录它的父结点,每次合并后往上查找是否有需要更新的值,有则更新(注意这时不能再使用路径压缩了)。
函数具体代码如下:
上传操作($\texttt{pushUp}$ )
```cppvoid pushUp(int x){ if(!x) return; if(dist(x) != dist(r(x)) + 1){ dist(x) = dist(r(x)) + 1; pushUp(fa(x));//有更改才继续上传 pushUp(fa(x));//有更改才继续上传 }}```
14 行未改动下传操作($\texttt{pushDown}$)
```cppvoid pushDown(int x){ if(add(x) == 0 && mul(x) == 1) return;//小优化 if(add(x) == 0 && mul(x) == 1) return;//小优化 if(l(x)){ val(l(x)) *= mul(x); val(l(x)) += add(x); mul(l(x)) *= mul(x);6 行未改动 mul(r(x)) *= mul(x); add(r(x)) *= mul(x); add(r(x)) += add(x); } add(x) = 0,mul(x) = 1;//加法清零,乘法归一 add(x) = 0,mul(x) = 1;//加法清零,乘法归一}```
110 行未改动全部展开 val(i) = read(),cit(i) = read(),mul(i) = 1; if(root[cit(i)] == -1) root[cit(i)] = i; else root[cit(i)] = merge(root[cit(i)], i); }
for(int x = n;x >= 1;-- x){//作者开始没看见 fi<i,用拓扑处理的, T 到飞起 while(root[x] != -1 && h(x) > val(root[x])){ die(root[x]) = x;++ d(x); pushDown(root[x]);8 行未改动 if(root[f(x)] == -1) root[f(x)] = root[x]; else root[f(x)] = merge(root[f(x)], root[x]); } }
for(int i = 1;i <= n;++ i) printf("%lld\n", d(i)); for(int i = 1;i <= m;++ i) printf("%lld\n", dep[cit(i)] - dep[die(i)]);55 行未改动```cppint merge(int x,int y){ if(!x | !y) return x | y; if(val(x) > val(y)) swap(x, y); int cnt = ++ idx;//新建一个结点 l(cnt) = l(x),val(cnt) = val(x);//继承 r(cnt) = merge(r(x), y);//以下为基础操作 int cnt = ++ idx;//新建一个结点 l(cnt) = l(x),val(cnt) = val(x);//继承 r(cnt) = merge(r(x), y);//以下为基础操作 if(dist(l(cnt)) < dist(r(cnt))) swap(l(cnt), r(cnt)); dist(cnt) = dist(r(cnt)) + 1; return cnt;}39 行未改动