洛谷 P3374 【模板】树状数组 1

【模板】树状数组 1 - 洛谷https://www.luogu.com.cn/problem/P3374

【树状数组】用树状数组来求前缀和:

1.树状数组从0-n开n+1个点,其中下标1到n存数

2.lowbit操作为 x & -x

3.插入操作: while(x <= n) { tree[x] = val; x += lowbit(x); }

4.查询操作: int ret = 0; while(n > 0) { ret += tree[x]; x -= lowbit(x); }


import java.io.*;

public class Main {

    public static int[] tree;
    public static int m, n;

    public static int lowbit(int x){
        return x & -x;
    }

    public static void add(int x, int val){
        while(x <= m){
            tree[x] += val;
            x += lowbit(x);
        }
    }

    public static int ask(int x){
        int ret = 0;
        while(x > 0){
            ret += tree[x];
            x -= lowbit(x);
        }
        return ret;
    }

    public static void main(String[] args) throws IOException{
        StreamTokenizer sc = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        sc.nextToken();
        m = (int)sc.nval;
        sc.nextToken();
        n = (int)sc.nval;
        tree = new int[m + 1];
        int i, j, x, y, t;
        for(i = 0; i < m; i++){
            sc.nextToken();
            x = (int)sc.nval;
            add(i + 1, x);
        }
        for(i = 0; i < n; i++){
            sc.nextToken();
            t = (int)sc.nval;
            sc.nextToken();
            x = (int)sc.nval;
            sc.nextToken();
            y = (int)sc.nval;
            if(t == 1){
                add(x, y);
            }else{
                System.out.println(ask(y) - ask(x - 1));
            }
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值