ACM-ICPC 2018 徐州赛区网络预赛H Ryuji doesn't want to study(树状数组)题解

时间:2021-03-04 03:52:38

题意:给你数组a,有两个操作 1 l r,计算l到r的答案:a[l]×L+a[l+1]×(L−1)+⋯+a[r−1]×2+a[r] (L is the length of [ l, r ] that equals to r - l + 1),或者 2 i b:把第i个换成b

思路:用一个树状数组存i的前缀和,再用一个树状数组存(n - i + 1)*a[ i ]的前缀和,这样算出后面那个的区间差减去前一个的区间差的某个倍数就会成为答案。

代码:

#include<queue>
#include<cstring>
#include<set>
#include<map>
#include<stack>
#include<cmath>
#include<vector>
#include<cstdio>
#include<iostream>
#include<algorithm>
typedef long long ll;
const int maxn = + ;
const int seed = ;
const ll MOD = 1e9 + ;
const int INF = 0x3f3f3f3f;
using namespace std;
ll sum[][maxn], a[maxn];
ll n;
int lowbit(int x){
return x&(-x);
}
void update(int x, ll v, int id){
for(int i = x; i <= n; i += lowbit(i)){
sum[id][i] += v;
}
}
ll query(int x, int id){
ll cnt = ;
for(int i = x; i > ; i -= lowbit(i)){
cnt += sum[id][i];
}
return cnt;
}
int main(){
ll q;
while(~scanf("%lld%lld", &n, &q)){
memset(sum, , sizeof(sum));
for(int i = ; i <= n; i++){
scanf("%lld", &a[i]);
update(i, a[i], );
update(i, a[i] * (n - i + ), );
}
while(q--){
ll u, v, w;
scanf("%lld%lld%lld", &u, &v, &w);
if(u == ){
printf("%lld\n", query(w, ) - query(v - , ) - (n - w) * (query(w, ) - query(v - , )));
}
else{
update(v, -a[v] + w, );
update(v, (-a[v] + w) * (n - v + ), );
a[v] = w;
}
}
}
return ;
}