No.137- LeetCode307 - 线段树模板题

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);}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值