跳到正文

个人记录

线段树

clx2024约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年2月25日
更新
2026年2月25日
篇幅
约 4 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
#define int long long
const int N = 5e5 + 5;  // 简化写法,ll 多余,long long 定义已覆盖
using namespace std;

int n, q, a[N];
struct point {
    int l, r, sum, add;
} tr[N * 4];

// 构建线段树(必须在 a 数组初始化后调用)
void build(int p, int l, int r) {
    tr[p].l = l;
    tr[p].r = r;
    tr[p].add = 0;  // 修复:初始化懒标记,避免随机值
    if (l == r) {
        tr[p].sum = a[l];
        return;
    }
    int mid = (l + r) >> 1;
    build(p << 1, l, mid);
    build(p << 1 | 1, mid + 1, r);
    tr[p].sum = tr[p << 1].sum + tr[p << 1 | 1].sum;
}

// 下推懒标记
void pushdown(int p) {
    if (tr[p].add) {
        auto &lc = tr[p << 1], &rc = tr[p << 1 | 1];
        lc.sum += tr[p].add * (lc.r - lc.l + 1);
        rc.sum += tr[p].add * (rc.r - rc.l + 1);
        lc.add += tr[p].add;
        rc.add += tr[p].add;
        tr[p].add = 0;
    }
}

// 区间更新:[x,y] 加 k
void update(int p, int x, int y, int k) {
    if (x <= tr[p].l && tr[p].r <= y) {
        tr[p].sum += k * (tr[p].r - tr[p].l + 1);
        tr[p].add += k;
        return;
    }
    pushdown(p);
    int mid = (tr[p].l + tr[p].r) >> 1;
    if (x <= mid) update(p << 1, x, y, k);
    if (y > mid) update(p << 1 | 1, x, y, k);
    tr[p].sum = tr[p << 1].sum + tr[p << 1 | 1].sum;
}

// 区间查询:[x,y] 的和(修复累加逻辑)
int find(int p, int x, int y) {
    if (x <= tr[p].l && tr[p].r <= y) {
        return tr[p].sum;
    }
    pushdown(p);
    int res = 0, mid = (tr[p].l + tr[p].r) >> 1;
    if (x <= mid) res += find(p << 1, x, y);  // 累加左子树结果
    if (y > mid) res += find(p << 1 | 1, x, y);  // 累加右子树结果
    return res;
}

signed main() {
    // 加速输入输出,避免超时/RE
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    // 修复:先读入数组,再构建线段树
    scanf("%lld%lld", &n, &q);
    for (int i = 1; i <= n; i++) {
        scanf("%lld", &a[i]);
    }
    build(1, 1, n);  // 此时 a 数组已初始化,build 正确

    while (q--) {
        int f;
        scanf("%lld", &f);
        if (f == 1) {
            int ll, rr, u;
            scanf("%lld%lld%lld", &ll, &rr, &u);
            update(1, ll, rr, u);
        } else {
            int kk;
            scanf("%lld", &kk);  // 修复:%lld 匹配 long long
            printf("%lld\n", find(1, kk, kk));  // 用 printf 避免 cout 效率问题
        }
    }
    return 0;
}
原文