题目:
-
第一类指令形如“C l r d”,表示把数列中第l~r个数都加d。
-
第二类指令形如“Q X”,表示询问数列中第x个数的值。
分析树状数组
- 修改某一个元素
- 求前缀和
差分
可以用差分的思想,完成题目的求法。
差分: b1 + b2 + … bn = an
-> b1 = a1 - a0
-> b2 = a2 - a1
…
import java.io.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static int[] tr, a;
static int n, m;
public static void main(String[] args) throws Exception{
String[] ss = read.readLine().split(" ");
n = Integer.valueOf(ss[0]); m = Integer.valueOf(ss[1]);
tr = new int[n + 1]; a = new int[n + 1];
ss = read.readLine().split(" ");
for(int i = 1; i <= n; i++) {
a[i] = Integer.valueOf(ss[i - 1]);
add(i, a[i] - a[i - 1]);
}
while(m -- > 0){
ss = read.readLine().split(" ");
switch(ss[0]){
case "C":
int l = Integer.valueOf(ss[1]);
int r = Integer.valueOf(ss[2]);
int c = Integer.valueOf(ss[3]);
add(l, c); add(r + 1, -c);
break;
case "Q":
int x = Integer.valueOf(ss[1]);
log.write(sum(x) + "\n");
break;
}
}
log.flush();
}
public static void add(int x, int c){
for(int i = x; i <= n; i += lowBit(i)) {
tr[i] += c;
}
}
public static long sum(int r){
long res = 0;
for(int i = r; i > 0; i -= lowBit(i)) res += tr[i];
return res;
}
public static int lowBit(int x){
return x & - x;
}
}