09-17更新:针对评论区的错误,原来是在推懒标记的时候需要 += 而不是 =。提供了更新后的测试:
int main() {
SegTree st;
st.upDate(st.root_, 0, 1e9, 5, 10, 2);
st.upDate(st.root_, 0, 1e9, 2, 7, 3);
cout << st.query(st.root_, 0, 1e9, 6, 6) << endl;
cout << st.query(st.root_, 0, 1e9, 7, 7) << endl;
cout << st.query(st.root_, 0, 1e9, 8, 8) << endl;
cout << st.query(st.root_, 0, 1e9, 6, 8) << endl;
cout << "-----------------------" << endl;
cout << st.query(st.root_, 0, 1e9, 1, 1) << endl;
cout << st.query(st.root_, 0, 1e9, 2, 2) << endl;
cout << st.query(st.root_, 0, 1e9, 3, 3) << endl;
cout << st.query(st.root_, 0, 1e9, 4, 4) << endl;
cout << st.query(st.root_, 0, 1e9, 5, 5) << endl;
cout << st.query(st.root_, 0, 1e9, 6, 6) << endl;
cout << st.query(st.root_, 0, 1e9, 7, 7) << endl;
cout << st.query(st.root_, 0, 1e9, 8, 8) << endl;
cout << st.query(st.root_, 0, 1e9, 9, 9) << endl;
cout << st.query(st.root_, 0, 1e9, 10, 10) << endl;
cout << st.query(st.root_, 0, 1e9, 11, 11) << endl;
return 0;
}
结果:

1. 问题背景
线段树主要是针对区间问题而生的一种数据结构。当频繁的对某个区间的元素(或者某个元素)进行加减后,再求某个区间的和就可以使用线段树来实现快速的查询。
在实现上,线段树一般使用二叉树来实现(即使是使用数组,也是模拟了完全二叉树)。假设我现在有数组如下:
nums=[3,5,1,1,2]。那么,根据这个数组可以拆分

本文详细介绍了线段树的数据结构及其在区间修改和查询上的应用,通过代码实现展示了如何利用动态开点和懒惰标记提高效率。线段树通过二叉树结构维护区间信息,支持快速更新和查询,特别适用于频繁修改和查询的场景。文中还通过LeetCode的题目实例说明了线段树在实际问题中的运用。
最低0.47元/天 解锁文章
810

被折叠的 条评论
为什么被折叠?



