You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

##P3368 【模板】树状数组 2

  • 知识点:区间修改,单点查询

通过 差分(就是记录数组中每个元素与前一个元素的差),可以把这个问题转化为问题 单点修改,区间查询

查询

设原数组为a[i], 设数组b[i]=a[i]-a[i-1](a[0]=0),则\displaystyle a[i]=\sum_{j=1}^{i}b[j],可以通过求b[i]的前缀和查询。

修改

当给区间[l,r]加上x的时候,a[l]与前一个元素 a[l-1]的差增加了xa[r+1]a[r]的差减少了x。根据b[i]数组的定义,只需给a[l]加上x, 给 a[r+1]减去x即可。

#include <bits/stdc++.h>
using namespace std;

const int N = 5e5 + 10;
int a[N]; // a是原数组。t是差分数组用树状数组维护

int n, m;
// 树状数组模板
#define lowbit(x) (x & -x)
int c[N];
void add(int x, int v) {
    while (x < N) c[x] += v, x += lowbit(x);
}
int sum(int x) {
    int res = 0;
    while (x) res += c[x], x -= lowbit(x);
    return res;
}

int main() {
    scanf("%d %d", &n, &m);

    // 原数组
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);

    int op, l, r, v, k;
    while (m--) {
        scanf("%d", &op);
        if (op == 1) {
            scanf("%d %d %d", &l, &r, &v);
            add(l, v), add(r + 1, -v);
        } else {
            scanf("%d", &k);
            // 树状数组维护的是变化量,还需要加上原来的值
            printf("%d\n", a[k] + sum(k)); // 求某点的值
        }
    }

    return 0;
}

也可以这样:

#include <bits/stdc++.h>
using namespace std;

const int N = 5e5 + 10;
int a[N]; // a是原数组。c是差分数组用树状数组维护

int n, m;
// 树状数组模板
#define lowbit(x) (x & -x)
int c[N];
void add(int x, int v) {
    while (x < N) c[x] += v, x += lowbit(x);
}
int sum(int x) {
    int res = 0;
    while (x) res += c[x], x -= lowbit(x);
    return res;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("P3368.in", "r", stdin);
#endif
    scanf("%d %d", &n, &m);

    // 原数组
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);

    // 保存差分数组
    for (int i = 1; i <= n; i++) add(i, a[i] - a[i - 1]);

    int op, l, r, v, k;
    while (m--) {
        scanf("%d", &op);
        if (op == 1) {
            scanf("%d %d %d", &l, &r, &v);
            add(l, v), add(r + 1, -v);
        } else {
            scanf("%d", &k);
            // 树状数组维护的是变化量,还需要加上原来的值
            printf("%d\n", sum(k)); // 求某点的值
        }
    }

    return 0;
}