跳到正文

题解

题解:AT_abc451_c [ABC451C] Understory

want_be_handsome_cat约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年3月31日
收录
2026年6月5日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前

发现只有一片题解使用的线段树,而且还比我复杂于是就来写一篇关于线段树的题解。

仅供参考,这道题我调了很久,T4都做出来了之后才做出来的。

大概题意:

给定 q 次操作:

1.将数组中添加一个数 h。

2.去掉数组中小于等于 h 的数。

最后求每次操作后的数组长度。

这一道题维护数量,一眼权值线段树,于是我就傻傻地开始写了。

首先是定义线段树:

C++
struct Segment_Tree {
    int l, r;
    int num; // 个数
    int add; // 懒标记
} tree[N * 4];

然后是各个操作:

  1. 下传懒标记
C++
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;
    }
}
  1. 建树
C++
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;
}
  1. 单点修改
C++
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;
}
  1. 清空
C++
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;
}

最后记得离散化就行

代码
原文