Advertisement
LLIAMA3OB

SegmentTree

Feb 21st, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. class SegmentTree<T> {
  2.  
  3.     interface Operation<T> {
  4.         T operation(T x, T y);
  5.  
  6.         T Null();
  7.     }
  8.  
  9.     Operation<T> operation;
  10.     T[] a;
  11.     int size;
  12.  
  13.     SegmentTree(T[] array, Operation<T> operation) {
  14.         this.operation = operation;
  15.         size = 1;
  16.         while (size < array.length) size *= 2;
  17.         a = (T[]) new Object[2 * size - 1];
  18.         for (int i = 0; i < array.length; i++) a[size + i - 1] = array[i];
  19.         for (int i = array.length; i < size; i++) a[size + i - 1] = operation.Null();
  20.         for (int i = size - 2; i >= 0; i--) a[i] = operation.operation(a[2 * i + 1], a[2 * i + 2]);
  21.     }
  22.  
  23.     void remove(int index) {
  24.         a[index] = operation.Null();
  25.         while (index > 0) {
  26.             index = (index - 1) / 2;
  27.             a[index] = operation.operation(a[index * 2 + 1], a[index * 2 + 2]);
  28.         }
  29.     }
  30.  
  31.     void set(int index, T value) {
  32.         index += size - 1;
  33.         a[index] = value;
  34.         while (index > 0) {
  35.             index = (index - 1) / 2;
  36.             int i2 = index * 2;
  37.             a[index] = operation.operation(a[i2 + 1], a[i2 + 2]);
  38.         }
  39.     }
  40.  
  41.     T get(int left, int right) {
  42.         return get(left - 1, right - 1, 0, size - 1, 0);
  43.     }
  44.  
  45.     T get(int left, int right, int l, int r, int root) {
  46.         if (left > r || right < l) {
  47.             return operation.Null();
  48.         }
  49.         if (left <= l && right >= r) {
  50.             return a[root];
  51.         }
  52.         int mid = (l + r) / 2;
  53.         root *= 2;
  54.         return operation.operation(get(left, right, l, mid, root + 1), get(left, right, mid + 1, r, root + 2));
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement