树状数组 区间修改,单点查询

https://www.luogu.com.cn/problem/P3368#ide

需要构造出原数组的差分数组d,然后用树状数组维护c数组

对于区间修改的话,我们只需要对差分数组进行操作即可,例如对区间[L,R]+k,那么我们只需要更新差分数组add(L,k),add(R+1,-k)

#include <bits/stdc++.h>
using namespace std;
vector<int> c;
int lowbit(int x){
    return x&-x;
}
void update(int i, int k){
    while(i < c.size()){
        c[i] += k;
        i+=lowbit(i);
    }
}
int query(int x){
    int ax = 0;
    for(int i =x; i > 0; i-=lowbit(i)){
        ax += c[i];
    }
    return ax;
}
int main(){
    int n,m;
    cin >> n >>m;
    vector<int> a(n+1);
    vector<int> d(n);
    c.resize(n+1);
    for(int i =1; i <= n; i++){
        cin>>a[i];
        d[i] = a[i]-a[i-1];
        update(i, d[i]);
    }
    int choice;
    while(m--){
        cin >> choice;
        if(choice == 1){
            int x,y,k;
            cin >> x >> y >> k;
            update(x, k);
            update(y+1, -k);
        }else {
            int x;
            cin >> x;
            cout << query(x) <<endl;
        }
    }
}

 

posted @ 2025-07-06 20:30  最近饭吃的很多  阅读(3)  评论(0)    收藏  举报