树状数组.java 2.1 KB
Newer Older
qq_36480062's avatar
c  
qq_36480062 已提交
1
package 树状数组;
qq_36480062's avatar
c  
qq_36480062 已提交
2

qq_36480062's avatar
c  
qq_36480062 已提交
3 4 5 6 7 8 9 10 11 12 13
import java.io.*;
import java.util.StringTokenizer;

import static java.lang.System.in;

/**
 * 单点修改,区间查询
 * https://www.luogu.com.cn/problemnew/solution/P3368
 * tle2个
 */

qq_36480062's avatar
c  
qq_36480062 已提交
14
public class 树状数组 {
qq_36480062's avatar
c  
qq_36480062 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    static BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    static StringTokenizer tokenizer = new StringTokenizer("");

    static String nextLine() throws IOException {// 读取下一行字符串
        return reader.readLine();
    }

    static String next() throws IOException {// 读取下一个字符串
        while (!tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {// 读取下一个int型数值
        return Integer.parseInt(next());
    }

    static double nextDouble() throws IOException {// 读取下一个double型数值
        return Double.parseDouble(next());
    }

    public static void main(String[] args) throws IOException {
        n = nextInt();
        m = nextInt();
        for (int i = 1; i <= n; i++) {
            add(i, nextInt());
qq_36480062's avatar
c  
qq_36480062 已提交
43
        }
qq_36480062's avatar
c  
qq_36480062 已提交
44 45 46 47 48 49 50 51 52 53 54 55
        int x, y, z;
        while (m-- != 0) {
            x = nextInt();
            if (x == 1) {
                y = nextInt();
                z = nextInt();
                add(y, z);
            } else {
                y = nextInt();
                z = nextInt();
                bw.write(query(y, z ) + "\n");
            }
qq_36480062's avatar
c  
qq_36480062 已提交
56
        }
qq_36480062's avatar
c  
qq_36480062 已提交
57
        bw.flush();
qq_36480062's avatar
c  
qq_36480062 已提交
58 59
    }

qq_36480062's avatar
c  
qq_36480062 已提交
60 61
    static int[] par = new int[500005];
    static int n, m;
qq_36480062's avatar
c  
qq_36480062 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

    static void add(int i, int x) {
        while (i <= n) {
            par[i] += x;
            i += lowbit(i);
        }
    }

    private static int lowbit(int i) {
        return i & -i;
    }

    static int query(int l, int r) {
        return get(r) - get(l - 1);
    }

    static int get(int x) {
        int res = 0;
        while (x != 0) {
            res += par[x];
            x -= lowbit(x);
        }
        return res;
    }
}