树状数组的区间加法(差分)

应用差分原理,实现树状数组区间加法
差分:a区间[1, 2, 3, 4, 5],则差分区间为[1, 1, 1, 1, 1]即bn = an - an-1,an = b1 +…+ bn
如果对区间[2, 4]都加上2,则a[1, 5, 6, 7, 5], 差分区间[1, 4, 1, 1, -2],区间增加时只需修改差分区间的左端点的值和右端点右边的值

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

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, m, op;
    ll x, y, k;
    cin >> n >> m;
    vector<ll> tre((n << 1) + 5);
    vector<ll> a(n + 1), b(n + 1);
    function<void(int, ll)> update = [&](int pos, ll val) {
        while(pos <= n) {
            tre[pos] += val;
            pos += pos & -pos;
        }
        return;
    };
    function<ll(int)> query = [&](int pos) {
        ll ret = 0;
        while(pos) {
            ret += tre[pos];
            pos -= pos & -pos;
        }
        return ret;
    };
    ll last = 0, now;
    for(int i = 1; i <= n; i++) {
        cin >> now;
        update(i, now - last);
        last = now;
    }
    while(m--) {
        cin >> op;
        if(op == 1) {
            cin >> x >> y >> k;
            update(x, k);
            update(y + 1, -k);
        }
        else {
            cin >> x;
            cout << query(x) << '\n';
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40588429/article/details/84716235