BIT.cc 626 B

123456789101112131415161718192021222324252627282930313233
  1. #define LOGSZ 17
  2. int tree[(1<<LOGSZ)+1];
  3. int N = (1<<LOGSZ);
  4. // add v to value at x
  5. void set(int x, int v) {
  6. while(x <= N) {
  7. tree[x] += v;
  8. x += (x & -x);
  9. }
  10. }
  11. // get cumulative sum up to and including x
  12. int get(int x) {
  13. int res = 0;
  14. while(x) {
  15. res += tree[x];
  16. x -= (x & -x);
  17. }
  18. return res;
  19. }
  20. // get largest value with cumulative sum less than or equal to x;
  21. // for smallest, pass x-1 and add 1 to result
  22. int getind(int x) {
  23. int idx = 0, mask = N;
  24. while(mask && idx < N) {
  25. int t = idx + mask;
  26. if(x >= tree[t]) {
  27. idx = t;
  28. x -= tree[t];
  29. }
  30. mask >>= 1;
  31. }
  32. return idx;
  33. }