题目链接 https://nanti.jisuanke.com/t/A2007
题目
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, ccrepresents [ 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
思路 https://blog.csdn.net/qq_37291934/article/details/89852059
AC代码
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
long long n,m;
long long c1[500005],c2[500005],num[500005];
long long lowbit(long long x)
{
return x&(-x);
}
void add(long long *s,long long pos,long long v)
{
while(pos<=n){
s[pos]+=v;
pos+=lowbit(pos);
}
}
long long query(long long *s,long long pos)
{
long long sum=0;
while(pos){
sum+=s[pos];
pos-=lowbit(pos);
}
return sum;
}
int main()
{ long long f,a,b,v;
while(scanf("%lld%lld",&n,&m)!=EOF){
int hh;
for(int i=1;i<=n;i++){
scanf("%lld",&num[i]);
add(c1,i,num[i]);
add(c2,i,(i-1)*num[i]);
}
for(int i=1;i<=m;i++){
scanf("%lld",&f);
if(f==2){
scanf("%lld%lld",&a,&b);
add(c1,a,-num[a]);
add(c1,a,b);
add(c2,a,(-num[a])*(a-1));
add(c2,a,b*(a-1));
num[a]=b;
}
else if(f==1){
scanf("%lld%lld",&a,&b);
long long sum1=b*query(c1,a-1)-query(c2,a-1); // 注意这里的变化
long long sum2=b*query(c1,b)-query(c2,b);
printf("%lld\n",sum2-sum1);
}
}
}
return 0;
}