权值线段树

学习权值线段树前,请先掌握线段树相关知识。线段树

一,定义:

权值线段树是用于处理一个一维数组拥有的数字及其数量。通过线段树我们可以快速求取区间数量最多的数字

二,思维:

线段树的[l,r]表示区间从数字l到数字r,这个区间数字数量最多max就是l到r中的一个

1,建树

struct tree
{
	int l, r;
	int cnt, max;//cnt表示区间数量最多的数字的数量,max表示数量最多的数字
} t[N << 2];

void build(int l, int r, int p)
{
	if (l > r)return;
	t[p].l = l, t[p].r = r, t[p].cnt = 0;//初始化
	if (l == r)
		{
			t[p].max = l;
			return;
		}
	int mid = l + ((r - l) >> 1);
	build(l, mid, p << 1);
	build(mid + 1, r, p << 1 | 1);
}

2,更新

void update(int id, int p, int w)
{
	if (t[p].l == id && id == t[p].r)
		{
			t[p].cnt += w;
			return;
		}
	int mid = t[p].l + ((t[p].r - t[p].l) >> 1);
	if (mid >= id)update(id, p << 1, w);
	if (mid < id)update(id, p << 1 | 1, w);
	if (t[p << 1].cnt >= t[p << 1 | 1].cnt)t[p].cnt = t[p << 1].cnt, t[p].max = t[p << 1].max;
	else t[p].cnt = t[p << 1 | 1].cnt, t[p].max = t[p << 1 | 1].max;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值