樹狀數組模板

已知一個數列,你需要進行下面兩種操作:
1.將某區間每一個數數加上x
2.求出某一個數的和
這種水水的樹狀數組,博主就不做介紹,直接上代碼,希望大家可以多多捧場!

#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>

using namespace std;

#define REP(i, a, b) for(int i = (a), _end_ = (b); i <= _end_; ++ i)

const int maxn = 500010;

int n, m;

int a[maxn], c[maxn];

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

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

int Getsum(int x) {
    int sum = 0;
    for(int i = x;i > 0; i -= Lowbit(i))
        sum += c[i];
    return sum;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    scanf("%d%d", &n, &m);
    REP(i, 1, n) {
        scanf("%d", &a[i]);
        add(i, a[i] - a[i - 1]);
    }
    int k, l, r, val;
    REP(i, 1, m) {
        scanf("%d", &k);
        if(k == 1) {
            scanf("%d%d%d", &l, &r, &val);
            add(l, val);add(r + 1, -val);
        }
        else {
            scanf("%d", &val);
            printf("%d\n", Getsum(val));
        }
    }
    return 0;
}
發佈了24 篇原創文章 · 獲贊 17 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章