树状数组

#include <bits/stdc++.h>
#include <unordered_map>

//数状数组;
using namespace std;
class Solution {
private:
    int lowbit(int x)
    {
        return x & -x;
    }
    vector<int> arr;
    vector<int> tree;
public:
    Solution(vector<int> & nums){
        arr = nums;
        int n = arr.size();
        arr.insert(arr.begin(),0);
        tree.resize(n+1,0);
        for(int i =1;i<=n;i++){
            for(int j = i- lowbit(i)+1;j<=i;j++){
                tree[i] += arr[j];
            }
        }
    };
    //查询nums数组包含index下标值的前缀和
    int query(int index){
        index+= 1;
        int sum = 0;
        while(index>0){
            sum += tree[index];
            index -= lowbit(index);
        }
        return sum;
    }
    //在num数组的下标index处,加delta;
    void add(int index,int delta){
        index+=1;
        while(index < arr.size()){
            tree[index] += delta;
            index += lowbit(index);
        }
    }
};
int main(){
    vector<int> nums={1,2,3,4,5,6};
    Solution * a =new Solution(nums);
    int b = a->query(2);
    a->add(1,3);
    int b1 = a->query(3);
    return 0;
}

 

posted @ 2022-06-19 15:58  coyote25  阅读(17)  评论(0编辑  收藏  举报