树状数组模板

文章介绍了如何在Java中利用树状数组数据结构来处理区间更新和单点查询问题,分别展示了两种方法,一种是直接维护原数组,另一种是维护差分数组。
摘要由CSDN通过智能技术生成

单点更新 区间查询

使用树状数组维护原数组即可

public class Test01 {
    static final int N = 10010;
    static int[] c = new int[N];
    static int n;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        for (int i = 1; i <= n; i++) {
            int x = in.nextInt();
            update(i, x);
        }

        // 这里执行单点修改的代码

        // q个查询,区间查询
        int q = in.nextInt();
        while (q-- > 0) {
            int l, r;
            l = in.nextInt();
            r = in.nextInt();
            System.out.println(sums(r) - sums(l - 1));
        }
    }

    /**
     * 更新原数组中的idx
     *
     * @param idx
     * @param x
     */
    public static void update(int idx, int x) {
        while (idx <= n) {
            c[idx] += x;
            idx += idx & -idx;
        }
    }

    /**
     * 求原数组中a[1...j]的和
     *
     * @param j
     * @return
     */
    public static int sums(int j) {
        int res = 0;
        while (j > 0) {
            res += c[j];
            j -= j & -j;
        }
        return res;
    }
}

区间更新 单点查询

使用树状数组维护原数组的差分数组

/**
 * 树状数组
 * 区间修改 单点查询
 * 使用树状数组维护原数组的差分数组
 */
public class Test02 {
    static final int N = 10010;
    static int[] c = new int[N];
    static int[] d = new int[N];
    static int n;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        for (int i = 1; i <= n; i++) {
            int x = in.nextInt();
            update(i, x);
            update(i + 1, -x);
        }

        // 这里执行区间修改的代码

        // 单点查询,输出原数组
        for(int i = 1; i <= n; i ++){
            System.out.print(getsum(i) + " ");
        }
    }

    /**
     * 如果对区间a[l...r]+x 即 update(l, x);update(r + 1, -x);
     * @param idx
     * @param x
     */
    public static void update(int idx, int x) {
        while (idx <= n) {
            c[idx] += x;
            idx += idx & -idx;
        }
    }

    /**
     * 求原数组a[j]
     * @param j
     */
    public static int getsum(int j) {
        int res = 0;
        while(j > 0){
            res += c[j];
            j -= j & -j;
        }
        return res;
    }
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值