leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

segment_tree.cpp (619B)


      1 class SegmentTree {
      2     const int n;
      3     vector<int> t = vector<int>(2 * n);
      4 
      5 public:
      6     SegmentTree(const vector<int> nums): n(size(nums)) {
      7         for (int i = 0; i < n; i++) t[n + i] = nums[i];
      8         for (int i = n - 1; i > 0; i--) t[i] = t[i * 2] + t[i * 2 + 1];
      9     }
     10 
     11     int sum(int l, int r) const {
     12         int res = 0;
     13 
     14         for (l += n, r += n; l < r; l /= 2, r /= 2)  {
     15             if (l & 1) res += t[l++];
     16             if (r & 1) res += t[--r];
     17         }
     18 
     19         return res;
     20     }
     21 
     22     void update(int p, int val) {
     23         for (t[p += n] = val; p > 1; p /= 2) t[p / 2] = t[p] + t[p ^ 1];
     24     }
     25 };