Last active
August 29, 2015 14:03
-
-
Save aleksmitov/57e9ca412b5744db5658 to your computer and use it in GitHub Desktop.
Implementation of Interval Tree with recursive Binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <vector> | |
| #include <algorithm> | |
| #include <cstdlib> | |
| using namespace std; | |
| struct IntervalTree | |
| { | |
| vector<int> data, tree; | |
| int N; | |
| IntervalTree(const vector<int> &input) | |
| { | |
| data = input; | |
| N = data.size(); | |
| tree.resize(4*N); | |
| build(1, 0, N-1); | |
| } | |
| int get(int from, int to) | |
| { | |
| return get(1, 0, N-1, from, to); | |
| } | |
| void increment(int index, int value) | |
| { | |
| data[index] += value; | |
| increment(1, 0, N-1, index); | |
| } | |
| private: | |
| void increment(int p, int L, int R, int index) | |
| { | |
| if(L == R) | |
| { | |
| tree[p] = data[L]; | |
| return; | |
| } | |
| int mid = (L+R)/2; | |
| if(index <= mid) increment(left(p), L, mid, index); | |
| else increment(right(p), mid+1, R, index); | |
| int leftChild = tree[left(p)]; | |
| int rightChild = tree[right(p)]; | |
| tree[p] = leftChild + rightChild; | |
| } | |
| int get(int p, int L, int R, int from, int to) | |
| { | |
| if(L > to || R < from) return -1; | |
| if(L >= from && R <= to) return tree[p]; | |
| int mid = (L+R)/2; | |
| int val1 = get(left(p), L, mid, from, to); | |
| int val2 = get(right(p), mid+1, R, from, to); | |
| if(val1 == -1) return val2; | |
| if(val2 == -1) return val1; | |
| return val1 + val2; | |
| } | |
| void build(int p, int L, int R) | |
| { | |
| if(L == R) | |
| { | |
| tree[p] = data[L]; | |
| return; | |
| } | |
| int mid = (L + R) / 2; | |
| build(left(p), L, mid); | |
| build(right(p), mid+1, R); | |
| int leftChild = tree[left(p)]; | |
| int rightChild = tree[right(p)]; | |
| tree[p] = leftChild + rightChild; | |
| } | |
| int left(int index) | |
| { | |
| return index << 1; | |
| } | |
| int right(int index) | |
| { | |
| return (index << 1) + 1; | |
| } | |
| }; | |
| int main() | |
| { | |
| vector<int> aaa; | |
| for(int i = 0; i < 100; ++i) aaa.push_back(i); | |
| IntervalTree tree(aaa); | |
| int min = tree.get(1, 10); | |
| cout<<min<<endl; | |
| tree.increment(3, 1111111); | |
| min = tree.get(3, 4); | |
| cout<<min<<endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment