发现只有一片题解使用的线段树,而且还比我复杂于是就来写一篇关于线段树的题解。
仅供参考,这道题我调了很久,T4都做出来了之后才做出来的。
大概题意:
给定 q 次操作:
1.将数组中添加一个数 h。
2.去掉数组中小于等于 h 的数。
最后求每次操作后的数组长度。
这一道题维护数量,一眼权值线段树,于是我就傻傻地开始写了。
首先是定义线段树:
struct Segment_Tree {
int l, r;
int num; // 个数
int add; // 懒标记
} tree[N * 4];然后是各个操作:
- 下传懒标记
void push_down(int p) {
if (tree[p].add) {
tree[p << 1].num = 0;
tree[p << 1].add = 1;
tree[p << 1 | 1].num = 0;
tree[p << 1 | 1].add = 1;
tree[p].add = 0;
}
}- 建树
void build(int p, int l, int r) {
tree[p].l = l, tree[p].r = r;
tree[p].num = 0;
tree[p].add = 0;
if (l == r) {
return;
}
int mid = (l + r) / 2;
build(p << 1, l, mid);
build(p << 1 | 1, mid + 1, r);
tree[p].num = tree[p << 1].num + tree[p << 1 | 1].num;
}- 单点修改
void update(int p, int x, int k) {
if (tree[p].l == tree[p].r) {
tree[p].num += k;
return;
}
push_down(p);
int mid = (tree[p].l + tree[p].r) / 2;
if (x <= mid) update(p << 1, x, k);
else update(p << 1 | 1, x, k);
tree[p].num = tree[p << 1].num + tree[p << 1 | 1].num;
}- 清空
void clear(int p, int l, int r) {
if (l <= tree[p].l && tree[p].r <= r) {
tree[p].num = 0;
tree[p].add = 1;
return;
}
push_down(p);
int mid = (tree[p].l + tree[p].r) / 2;
if (l <= mid) clear(p << 1, l, r);
if (r > mid) clear(p << 1 | 1, l, r);
tree[p].num = tree[p << 1].num + tree[p << 1 | 1].num;
}最后记得离散化就行