题目链接:https://nanti.jisuanke.com/t/31460
Ryuji is not a good student, and he doesn't want to study. But there are n books he should learn, each book has its knowledge a[i]a[i].
Unfortunately, the longer he learns, the fewer he gets.
That means, if he reads books from ll to rr, he will get a[l] \times L + a[l+1] \times (L-1) + \cdots + a[r-1] \times 2 + a[r]a[l]×L+a[l+1]×(L−1)+⋯+a[r−1]×2+a[r] (LL is the length of [ ll, rr ] that equals to r - l + 1r−l+1).
Now Ryuji has qq questions, you should answer him:
11. If the question type is 11, you should answer how much knowledge he will get after he reads books [ ll, rr ].
22. If the question type is 22, Ryuji will change the ith book's knowledge to a new value.
Input
First line contains two integers nn and qq (nn, q \le 100000q≤100000).
The next line contains n integers represent a[i]( a[i] \le 1e9)a[i](a[i]≤1e9) .
Then in next qq line each line contains three integers aa, bb, cc, if a = 1a=1, it means question type is 11, and bb, cc represents [ ll , rr ]. if a = 2a=2 , it means question type is 22 , and bb, cc means Ryuji changes the bth book' knowledge to cc
Output
For each question, output one line with one integer represent the answer.
5 3 1 2 3 4 5 1 1 3 2 5 0 1 4 5
10 8
题解:树状数组维护前缀和。原式可转换为:sigma( r + 1 - i) * a[i] = ( r + 1) * sigma a[i] - sigma i * a[i]。然后基本上就是树状数组模板了。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define ll long long
using namespace std;
const int maxn = 100000+7;
int n, q;
ll a[maxn], b[maxn], c[maxn];
int lowbit(int x){
return x & -x;
}
void add(int x, ll y){
while(x <= n){
b[x] += y;
x += lowbit(x);
}
}
void Add(int x, ll y){
while(x <= n){
c[x] += y;
x += lowbit(x);
}
}
ll getsum1(int x){
ll sum = 0;
while(x > 0){
sum += b[x];
x -= lowbit(x);
}
return sum;
}
ll getsum2(int x) {
ll sum = 0;
while(x) {
sum += c[x];
x -= lowbit(x);
}
return sum;
}
int main()
{
scanf("%d %d", &n, &q);
for(int i = 1; i <= n; i++){
scanf("%lld", &a[i]);
add(i, a[i]);
Add(i, i*a[i]);
}
while(q--){
int op, l;
ll r;
scanf("%d %d %lld", &op, &l, &r);
if(op == 1){
ll t = getsum1(r) - getsum1(l-1);//求 l ~ r 中a[i]的和
ll temp = getsum2(r) - getsum2(l-1);//求 l ~ r 中 i*a[i]的和
printf("%lld\n", (r+1)*t - temp);
}else if(op == 2){
add(l, -a[l]);
Add(l, -l*a[l]);
a[l] = r;
add(l, a[l]);
Add(l, l*a[l]);
}
}
return 0;
}