BIT.cc 672 B

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