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

https://ac.nowcoder.com/acm/problem/15164

image

 

https://blog.csdn.net/TheWayForDream/article/details/118436732

求区间1-7的和=t[7]+t[6]+t[4]

求【x,y】的区间和

【x,y】=【1,y】-【1,x-1】

#include <bits/stdc++.h>
using namespace std;
vector<int> c;


int lowbit(int x) {
    return x & -x;
}
void update(int i, int ai ){
    while(i < c.size()){
        c[i] += ai;
        i+=lowbit(i);
    }
}
int query(int x, int y){
    int ans = 0;
    for (int i = y; i > 0; i-=lowbit(i)){
        ans+=c[i];
    }

    for (int i = x-1; i > 0; i-=lowbit(i)){
        ans-=c[i];
    }
    return ans;
}
int main(){
    int n,m;
    cin >> n >>m;
    vector<int> a(n + 1);

    c.resize(n+1);
    for (int i = 1; i <= n; i++){
        cin >> a[i];
        update(i, a[i]);
    }
    int choice, x, y;
    while (m --) {
        cin >> choice >> x >>y;
        if (choice == 1){
            update(x, y);
        }else {
            cout <<query(x,y) << endl;
        }
    }
}

 

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