学习权值线段树前,请先掌握线段树相关知识。线段树
一,定义:
权值线段树是用于处理一个一维数组拥有的数字及其数量。通过线段树我们可以快速求取区间数量最多的数字
二,思维:
线段树的[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;
}