【模板】树状数组 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));
}
}
}
}