Advertisement
adrienbrody2011

Segment Tree

Feb 4th, 2013
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. using System;
  2.  
  3. namespace SegmentTree {
  4.     class SegmentTree {
  5.         int l;
  6.         int r;
  7.         long add;
  8.         long sum;
  9.         SegmentTree lson, rson;
  10.  
  11.         public SegmentTree(int l, int r, int[] vals) {
  12.             this.l = l;
  13.             this.r = r;
  14.             this.add = 0;
  15.             this.sum = 0;
  16.             if (l != r) {
  17.                 this.lson = new SegmentTree(l, (l + r) / 2, vals);
  18.                 this.rson = new SegmentTree((l + r) / 2 + 1, r, vals);
  19.                 this.sum = this.lson.add + this.lson.sum + this.rson.add + this.rson.sum;
  20.             } else {
  21.                 this.lson = null;
  22.                 this.rson = null;
  23.                 this.add = vals[l];
  24.             }
  25.         }
  26.  
  27.         public void Add(int l, int r, long val) {
  28.             if (l > this.r || r < this.l) {
  29.                 return;
  30.             }
  31.             if (l <= this.l && r >= this.r) {
  32.                 this.add += val;
  33.                 return;
  34.             }
  35.             this.lson.Add(l, r, val);
  36.             this.rson.Add(l, r, val);
  37.             this.sum = this.lson.add * (this.lson.r - this.lson.l + 1) + this.lson.sum + this.rson.add * (this.rson.r - this.rson.l + 1) + this.rson.sum;
  38.         }
  39.  
  40.         public long Sum(int l, int r) {
  41.             if (l > this.r || r < this.l) {
  42.                 return 0;
  43.             }
  44.             if (l <= this.l && r >= this.r) {
  45.                 return this.add * (this.r - this.l + 1) + this.sum;
  46.             }
  47.             return this.add * (Math.Min(r, this.r) - Math.Max(l, this.l) + 1) + this.lson.Sum(l, r) + this.rson.Sum(l, r);
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement