題目大意:1~M個士兵,初始的時候,每個人的軍工都是零,動態連續增加軍工,動態查詢某個人的軍工!!
思路:由於是動態的,連續插入,單個查詢,是典型的插線問點樹狀數組!!!
對於樹狀數組的lowBit()、update()和getSum(),多了也就理解了,南陽理工的一些列的《士兵殺敵》做完,理解會更好!
import java.io.BufferedInputStream;
import java.util.Scanner;
public class Main {
static int[] arr = new int[1000005];
static int len;
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int cases;
String str;
cases = sc.nextInt();
len = sc.nextInt();
while (cases-- > 0) {
str = sc.next();
if (str.charAt(0) == 'A') {//看java源碼,這個效率高!
int start = sc.nextInt();
int end = sc.nextInt();
int add = sc.nextInt();
update(start, add);
update(end + 1, -add);//插線問點,前面增加add,後面要去掉!
} else {
System.out.println(getNum(sc.nextInt()));
}
}
sc.close();
}
static int lowBit(int x) {
return -x & x;
}
static void update(int x, int add) {
while (x <= len) {
arr[x] += add;
x += lowBit(x);
}
}
static int getNum(int x) {
int sum = 0;
while (x > 0) {
sum += arr[x];
x -= lowBit(x);
}
return sum;
}
}