class NumArray {
private:
struct Node{
int sum;
Node* left;
Node* right;
Node():sum(0),left(NULL),right(NULL){}
};
int N;
Node* root;
public:
NumArray(vector<int>& nums) {
N = nums.size();
root = build(0,N);
for(int i=0;i<N;i++) update(i,nums[i]);
}
Node* build(int L,int R){
Node* t = new Node();
if(L+1 >= R) return t;
int mid = (L+R)/2;
t->left = build(L,mid);
t->right = build(mid,R);
return t;
}
void updateA(Node* now,int loc,int L,int R,int key,int& T){
printf("<%d %d>\n",L,R);
if(L+1 >= R){
T = key - now->sum;
now->sum = key;
return ;
}
int mid = (L+R)/2;
if(loc < mid) updateA(now->left,loc,L,mid,key,T);
else updateA(now->right,loc,mid,R,key,T);
now->sum += T;
}
void update(int i, int val){
int t;
updateA(root,i,0,N,val,t);
}
int bsearch(Node* now,int l,int r,int L,int R){
if(l==L && r==R) return now->sum;
int mid = (L+R)/2;
if(r <= mid) return bsearch(now->left,l,r,L,mid);
if(l >= mid) return bsearch(now->right,l,r,mid,R);
return bsearch(now->left,l,mid,L,mid) + bsearch(now->right,mid,r,mid,R);
}
int sumRange(int i, int j) {return bsearch(root,i,j+1,0,N);}
};
No.137- LeetCode307 - 线段树模板题
最新推荐文章于 2022-08-27 23:07:26 发布