美文网首页线段树
树状数组模板

树状数组模板

作者: 江海小流 | 来源:发表于2019-12-23 17:35 被阅读0次
    # include <iostream>
    # include <cstdlib>
    
    class TreeArray {
        typedef long long value_t;
    
        private:
            value_t *p;
            int size;
        
        public:
            TreeArray(int n): size(n+1) {
                p = (value_t *)malloc(size * sizeof(value_t));
                for (int i = 0; i < size; i++) *(p+i) = 0;
            }
            
            ~TreeArray() {
                free(p);
            }
            
            void update(int i, value_t val) {
                for (; i < size; i += (i & -i)) {
                    *(p + i) += val;
                }
            }
            
            value_t sum(int i) {
                value_t ret = 0;
                for (; i > 0; i -= (i & -i)) {
                    ret += *(p + i);
                }
                return ret;
            }
    };
    
    int main(void) {
      TreeArray s(3);
      s.update(1, 1);
      s.update(2, 3);
      s.update(3, 5);
      printf("%lld\n", s.sum(3));
      s.update(2, 2);
      printf("%lld\n", s.sum(3));
    }
    

    [1] Leetcode 307. Range Sum Query - Mutable

    class NumArray {
    public:
        TreeArray s;
    
        NumArray(vector<int>& nums): s(nums.size()) {
            for (int i = 0; i < nums.size(); i++) {
                s.update(i+1, nums[i]);
            }
        }
        
        void update(int i, int val) {
            long long cur_val = this->sumRange(i, i);
            s.update(i+1, val-cur_val);
        }
        
        int sumRange(int i, int j) {
            return s.sum(j+1) - s.sum(i);
        }
    };
    

    相关文章

      网友评论

        本文标题:树状数组模板

        本文链接:https://www.haomeiwen.com/subject/thqtoctx.html