树状数组模板

#include <iostream>
#define MAXN 500005
#define lowbit(x) (x&(-x))
using namespace std;

int pre[MAXN];
int N,M;

inline int get_sum(int x) {
    int ans = 0;
    for(;x>0;x-=lowbit(x)) ans += pre[x];
    return ans;
}

inline void update(int x,int c) {
    for(;x<=N;x+=lowbit(x)) pre[x] += c;
}

int main() {

    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    cin >> N >> M;
    for(int i=1;i<=N;++i) {
        int a; cin >> a; update(i,a);
    }

    for(int i=1;i<=M;++i) {
        
        int opt,x,y;
        cin >> opt >> x >> y;

        if(opt==1) update(x,y);
        else cout << get_sum(y) - get_sum(x-1) << '\n';

    }

    return 0;
}

树状数组的区间修改+单点查询
使用差分

#include <iostream>
#define MAXN 500005
#define lowbit(x) (x&(-x))
using namespace std;

int pre[MAXN];
int N,M;

inline int get_sum(int x) {
    int ans = 0;
    for(;x>0;x-=lowbit(x)) ans += pre[x];
    return ans;
}

inline void update(int x,int c) {
    for(;x<=N;x+=lowbit(x)) pre[x] += c;
}

int main() {

    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    cin >> N >> M; int last = 0;
    for(int i=1;i<=N;++i) {
        int a; cin >> a; update(i,a-last); last = a;
    }

    for(int i=1;i<=M;++i) {
        
        int opt,x,y,k;
        cin >> opt >> x;

        if(opt==1) {
            cin >> y >> k; update(x,k); update(y+1,-k);
        }
        else cout << get_sum(x) << '\n';

    }

    return 0;
}
posted @ 2018-02-23 13:23  Neworld1111  阅读(97)  评论(0)    收藏  举报