image.png
image.png

一维

  1. public static class indexTree {
  2. //辅助数组
  3. private int[] tree;
  4. private int N;
  5. public indexTree(int size) {
  6. N = size;
  7. tree = new int[N + 1];
  8. }
  9. // 0 ~ index 范围上的累加和
  10. public int sum(int index) {
  11. int res = 0;
  12. while (index > 0) {
  13. res += tree[index];
  14. index -= index & -index;
  15. }
  16. return res;
  17. }
  18. // index位置的数,想加上d,还有哪些位置也要都加d
  19. public void add(int index, int d) {
  20. while (index <= N) {
  21. tree[index] += d;
  22. index += index & -index;
  23. }
  24. }
  25. }

二维

308题

三维