Akatsuki13

BIT

Oct 28th, 2016
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #define LOGSZ 17
  5.  
  6. int tree[(1<<LOGSZ)+1];
  7. int N = (1<<LOGSZ);
  8.  
  9. // add v to value at x
  10. void set(int x, int v) {
  11.   while(x <= N) {
  12.     tree[x] += v;
  13.     x += (x & -x);
  14.   }
  15. }
  16.  
  17. // get cumulative sum up to and including x
  18. int get(int x) {
  19.   int res = 0;
  20.   while(x) {
  21.     res += tree[x];
  22.     x -= (x & -x);
  23.   }
  24.   return res;
  25. }
  26.  
  27. // get largest value with cumulative sum less than or equal to x;
  28. // for smallest, pass x-1 and add 1 to result
  29. int getind(int x) {
  30.   int idx = 0, mask = N;
  31.   while(mask && idx < N) {
  32.     int t = idx + mask;
  33.     if(x >= tree[t]) {
  34.       idx = t;
  35.       x -= tree[t];
  36.     }
  37.     mask >>= 1;
  38.   }
  39.   return idx;
  40. }
Add Comment
Please, Sign In to add comment