IndexTree

IndexTree 树状数组

https://oi-wiki.org/ds/fenwick/
功能:单点修改 和 区间查询
注意:
普通树状数组维护的信息及运算要满足 结合律 且 可差分,如加法(和)、乘法(积)、异或等。

public class IndexTree {
    int N;
    int[] arr;

    public IndexTree(int N) {
        this.N = N + 1;
        arr = new int[N + 1];
    }

    // 在原始数组index位置的值+num
    public void add(int index, int num) {
        while (index < N) {
            arr[index] += num;
            index += index & -index;
        }
    }

    // 求原始数组arr[0, index]的累加和
    public int sum(int index) {
        int res = 0;
        while (index > 0) {
            res += arr[index];
            index -= index & -index;
        }
        return res;
    }
}

posted @ 2023-04-25 14:58  我见青山应如是  阅读(13)  评论(0编辑  收藏  举报