普通模板
初始化
struct Segtree
{
int l, r;
int dat;
}t[N*4];
void build(int p, int l, int r)
{
t[p].l = l, t[p].r = r;
if (l == r)
{
t[p].dat = a[l];
return;
}
int mid = (l + r) >> 1;
build (p*2, l, mid);
build (p*2+1, mid+1, r);
t[p].dat = max(t[p*2].dat, t[p*2+1].dat);
}
build (1, 1, n);
更改
void change (int p, int x, int v)
{
if (t[p].l == t[p].r)
{
t[p].dat = v;
return;
}
int mid = (t[p].l + t[p].r) >> 1;
if (x < mid) change (p*2+1, x, v);
t[p].dat = max(t[p*2].dat, t[p*2+1].dat);
}
change (1, x, v);
询问
int ask (int p, int l, int r)
{
if (l<=t[p].l && r>=t[p].r)
return t[p].dat;
int mid = (t[p].l + t[p].r) >> 1;
int val = -(1<<30);
if (l <= mid) val = max(val, ask(p*2, l, r));
if (r >= mid) val = max(val, ask(p*2+1, l, r));
return val;
}
cout << ask(1, l, r) << endl;
懒标记
懒标记只适合区间和等问题
标记
void spread (int p)
{
if (t[p].add)
{
t[p*2].dat += t[p].add*(t[p].r - t[p].l + 1);
t[p*2+1].dat += t[p].add*(t[p+1].r - t[p+1].l + 1);
t[p*2].add += t[p].add;
t[p*2+1].add += t[p].add;
t[p].add = 0;
}
}
初始化
struct Segtree
{
int l, r;
long long dat, add;
}t[N*4];
void build(int p, int l, int r)
{
t[p].l = l, t[p].r = r;
if (l == r)
{
t[p].dat = a[l];
return;
}
int mid = (l + r) >> 1;
build (p*2, l, mid);
build (p*2+1, mid+1, r);
t[p].dat = t[p*2].dat + t[p*2+1].dat;
}
更改
void change (int p, int l, int r, int d) //l到r的区间每个元素值加d
{
if (t[p].l == t[p].r)
{
t[p].dat += (long long)d * (t[p].r-t[p].l+1);
t[p].add += d;
return;
}
spread (p);
int mid = (t[p].l + t[p].r) >> 1;
if (l <= mid) change (p*2, l, r, d);
if (r >= mid) change (p*2+1, l, r, d);
t[p].dat = t[p*2].dat + t[p*2+1].dat;
}
询问
int ask (int p, int l, int r)
{
if (l<=t[p].l && r>=t[p].r)
return t[p].dat;
spread (p);
int mid = (t[p].l + t[p].r) >> 1;
long long val = 0;
if (l <= mid) val += ask(p*2, l, r);
if (r >= mid) val += ask(p*2+1, l, r);
return val;
}