AcWing 242. 一个简单的整数问题
原题链接
简单
作者:
花酱
,
2024-12-09 23:13:03
,
所有人可见
,
阅读 2
import java.util.Scanner;
class Main{
public static int n,m;
public static int[] tree;
public static int[] nums;
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
n=scan.nextInt();
m=scan.nextInt();
tree=new int[n];
nums=new int[n+1];
for (int i = 1; i <= n; i++) {
int t=scan.nextInt();
nums[i]=t;
}
for (int i = 1; i <= n; i++) {
//存的是差分
update(i,nums[i]-nums[i-1]);
}
for (int i = 0; i < m; i++) {
char t=scan.next().charAt(0);
if(t=='Q'){
int p=scan.nextInt();
System.out.println(count(p));
}else{
int l=scan.nextInt();
int r=scan.nextInt();
int val=scan.nextInt();
//跟差分的更新是一样的
update(l,val);
update(r+1,-val);
}
}
}
public static void update(int index,int val){
for (int i = index; i < tree.length; i+=i&-i) {
tree[i]+=val;
}
}
public static int count(int p){
//统计前p个数的和
int result=0;
while(p>0){
result+=tree[p];
p-=p&-p;
}
return result;
}
}