动态开点线段树(C++实现)

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


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]。那么,根据这个数组可以拆分

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值