[AcWing 242] 一个简单的整数问题

image
image

树状数组

区间修改,单点查询


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 2e5 + 10;

int n, m;
LL a[N];
LL tr[N];

int lowbit(int x)
{
    return x & -x;
}

void add(int x, int c)
{
    for (int i = x; i <= n; i += lowbit(i))
        tr[i] += c;
}

LL ask(int x)
{
    LL res = 0;
    for (int i = x; i; i -= lowbit(i))
        res += tr[i];
    return res;
}

void solve()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i ++) {
        cin >> a[i];
        add(i, a[i] - a[i - 1]);
    }
    while (m --) {
        char op;
        int x, l, r, d;
        cin >> op;
        if (op == 'Q') {
            cin >> x;
            cout << ask(x) << endl;
        }
        else {
            cin >> l >> r >> d;
            add(l, d);
            add(r + 1, -d);
        }
    }   
}   

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    solve();

    return 0;
}

  1. 使用树状数组维护差分数组的前缀和
posted @ 2022-07-19 21:31  wKingYu  阅读(33)  评论(0)    收藏  举报