线段树
线段树模板#
【AgOHの数据结构】线段树分裂合并_哔哩哔哩_bilibili线段树是一种可以维护满足结合律的区间信息的数据结构
P3372 【模板】线段树 1 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)P3374 【模板】树状数组 1 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
例题一#
Queue - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)题目大意: 给定 n
个正整数 a1…n。需要输出一个 n
个数,设此时正在处理第 i
个数: - 设 aj<ai,j>i。 - 在满足第一条的基础上使 j-i-1
尽可能大,此时 j - i - 1
即为答案。 2≤n≤105,ai≤109, 如果对于某个 i
,不存在任何一个 j
满足 aj<ai 且 j>i,则输出 -1
。
即找最远小于 a[i]
的值的位置
例题四#
P3373 【模板】线段树 2 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)一个线段树上同时进行两种操作区间乘以及区间加 代码:
例题三#
P 3740 [HAOI 2014] 贴海报 - 洛谷 | 计算机科学教育新生态 (luogu. Com. Cn)不需要建树的线段树,每一步大操作都是一次性的,且树上只存储少量的信息,在不建树的情况下可以节省很多空间复杂度
解题思路: 线段树维护区间是否被染色:区间修改没被染色的点,标记,++ans
;如果区间的点全被染过色,那ans
不变。 注意数据的处理顺序与输入顺序相反。因为最后输入的在最上面,一定可以ans++
,所以先处理,之后处理先输入的数据,如果它需要的区间已经被标记则表示它被后输入的覆盖了,于是不能ans++
,直接return
。可以结合代码在仔细理解
代码:
线段树分裂合并#
P 4556 [Vani 有约会]雨天的尾巴 /【模板】线段树合并_哔哩哔哩_bilibili
P5494 【模板】线段树分裂 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题意描述: 给出一个可重集 𝑎(编号为 1),它支持以下操作:
0 p x y
:将可重集 𝑝 中大于等于 𝑥且小于等于 𝑦 的值移动到一个新的可重集中(新可重集编号为从 2 开始的正整数,是上一次产生的新可重集的编号+1)。
1 p t
:将可重集 𝑡t 中的数放入可重集 𝑝,且清空可重集 𝑡(数据保证在此后的操作中不会出现可重集 𝑡)。
2 p x q
:在 𝑝这个可重集中加入 𝑥 个数字 𝑞。//也就是 r=l=q,val+=x;
3 p x y
:查询可重集 𝑝 中大于等于 𝑥x 且小于等于 𝑦 的值的个数。
4 p k
:查询在 𝑝 这个可重集中第 𝑘 小的数,不存在时输出 -1
。
输入格式
第一行两个整数 𝑛,𝑚n, m,表示可重集中的数在 1∼𝑛1∼n 的范围内,有 𝑚m 个操作。
接下来一行 𝑛n 个整数,表示 1∼𝑛1∼n 这些数在 𝑎a 中出现的次数 (𝑎𝑖≤𝑚)(ai≤m)。
接下来的 𝑚m 行每行若干个整数,第一个数为操作的编号 𝑜𝑝𝑡opt(0≤𝑜𝑝𝑡≤40≤opt≤4),以题目描述为准。
输出格式
依次输出每个查询操作的答案。
动态开点线段树#
C48 线段树+动态开点 CF915E Physical Education Lessons_哔哩哔哩_bilibili
模板题#
Physical Education Lessons - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
时间超时,但逻辑正确可参考学习
题二:#
T125847 【模板】动态开点线段树 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题三:#
P 3960 [NOIP 2017 提高组] 列队 - 洛谷 | 计算机科学教育新生态 (luogu. Com. Cn)
可持久化线段树(主席树)#
C49【模板】可持久化线段树(主席树)P3919 可持久化数组_哔哩哔哩_bilibili
代码实现#
例题:#
P3919 【模板】可持久化线段树 1(可持久化数组) - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
线段树标记永久化#
标记永久化:就是修改时留下的懒标记并不下穿,也不删除,而是留在打上标记的那一个节点上。当查询经过这个节点时,就加上这个节点的懒标记造成的影响。
因此:标记永久化不需要 pushdown 以及 pushup 操作,可以避免一些不必要的计算,来节省时间
线段树维护矩阵乘法#
矩阵乘法满足 结合律:(A*B)*C=A*(B*C) 分配律:A*(B+C)=A*B+A*C
线段树维护矩阵 - untitled0 - 博客园 (cnblogs.com)
线段树维护哈希#
线段树维护哈希 - zltzlt - 博客园 (cnblogs.com)