题目链接
塔子哥的收藏夹-美团2023笔试(codefun2000)
题目内容
输入描述
输出描述
样例1
输入
4 7
1 0 1 0 1 0 1
1 1 1 3 1 4 1
3 2 3 5 3 100 3
输出
0 2 7 7
提示
操作记录为
0 0 0 0(初始)
询问[1,3]结果为0+0+0>
2 0 0 0<1号更改为2>
<询问[1,3],结果为2+0+0>
2 0 5 0 <3号更改为5>
<询问[1,3]结果为2+0+5>
2 0 5 100<4号更改为100>
<询问[1,3],结果为2+0+5>
题解1(C++版本)
// 树状数组的应用
#include<bits/stdc++.h>
using namespace std;
const int N = 50005;
#define lowbit(x) ((x)&(-x))
int n, m, op[N], X[N], Y[N], tree[N], ans[N], cnt;
void update(int x, int val){ //修改元素tree[x], tree[x] += val
for(int i = x; i <= n; i += lowbit(i)){
tree[i] += val;
}
}
int getSum(int x){ //返回值是前缀和: sum = tree[1]+tree[2]+...+tree[x]
int sum = 0;
for(int i = x; i > 0; i -= lowbit(i)){
sum += tree[i];
}
return sum;
}
signed main(){
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++) scanf("%d", &op[i]);
for(int i = 1; i <= m; i++) scanf("%d", &X[i]);
for(int i = 1; i <= m; i++) scanf("%d", &Y[i]);
for(int i = 1; i <= m; i++){
if(op[i] == 0) {
int t = getSum(X[i]) - getSum(X[i] - 1);
update(X[i], -t); // 更新新的值之前,先还原
update(X[i], Y[i]);
}
else if(op[i] == 1) {
ans[++cnt] = getSum(Y[i]) - getSum(X[i] - 1);
}
}
for(int i = 1; i <= cnt; i++) {
if(i > 1) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
return 0;
}