树状数组的初步学习

29 阅读1分钟

发布技术文章,文章内首/尾句带关键词“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 22天,点击查看活动详情

树状数据组是一种支持单点修改区域查询的,代码量小的数据结构。

下面这张图展示了树状数组的工作原理:

image.png

例题:动态求连续区间和 给定 n 个数组成的一个数列,规定有两种操作,一是修改某个元素,二是求子数列 [a,b] 的连续和。

输入格式

第一行包含两个整数 n 和 m,分别表示数的个数和操作次数。

第二行包含 n 个整数,表示完整数列。

接下来 m 行,每行包含三个整数 k,a,b 

输出格式

输出若干行数字,表示 k=0 时,对应的子数列 [a,b]的连续和。

输入样例:

10 5
1 2 3 4 5 6 7 8 9 10
1 1 5
0 1 3
0 4 8
1 7 5
0 4 8

输出样例:

11
30
35
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    static int N = 100010;
    static int n;
    static int m;
    static int[] a = new int[N];
    static int[] tr = new int[N];

    public static int lowbit(int x)
    {
        return x & -x;
    }
    //在x位置加上v,并将后面相关联的位置也加上v
    public static void add(int x,int v)
    {
        for(int i = x;i <= n;i += lowbit(i)) tr[i] += v;
    }
    //前缀和
    public static int query(int x)
    {
        int res = 0;
        for(int i = x;i >= 1;i -= lowbit(i)) res += tr[i];
        return res;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] s1 = reader.readLine().split(" ");
        n = Integer.parseInt(s1[0]);
        m = Integer.parseInt(s1[1]);
        String[] s2 = reader.readLine().split(" ");
        for(int i = 1;i <= n;i++) a[i] = Integer.parseInt(s2[i - 1]);
        //搭建树状数组
        for(int i = 1;i <= n;i++) add(i,a[i]);

        while(m -- > 0)
        {
            String[] s3 = reader.readLine().split(" ");
            int k = Integer.parseInt(s3[0]);
            int x = Integer.parseInt(s3[1]);
            int y = Integer.parseInt(s3[2]);
            //k = 0 是询问[x,y]的区间和,k = 1是在x位置添加y元素
            if(k == 0) System.out.println(query(y) - query(x - 1));
            else add(x,y);
        }
    }
}