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
题目来源
思路:对于 a[1,n]分别乘以 n->1的值保存为 d[1,], a[1,n]的前缀和为sum[1,n]
那么选取 a[L,R] 时,观察可以发现 ans=d[L,R]-(n-R)*sum[L,R];
而对于a[]还要修改则用 线段树进行维护即可
Code :
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int MAX_N=100005;
int n,Q;
LL a[MAX_N],d[MAX_N],s[MAX_N];
LL sum[MAX_N<<2];
LL dd[MAX_N<<2];
void PushUp(int t);
void Build(int l,int r,int t);
void Update(int id,LL C,int l,int r,int t);
LL Query1(int L,int R,int l,int r,int t);
LL Query2(int L,int R,int l,int r,int t);
int main()
{
scanf("%d%d",&n,&Q);
for(int i=1;i<=n;++i)
{
scanf("%lld",&a[i]);
d[i]=a[i]*(n-i+1);
}
Build(1,n,1);
int p,l,r;
while(Q--){
scanf("%d%d%d",&p,&l,&r);
if(p==1){
LL ans=Query1(l,r,1,n,1)-(n-r)*Query2(l,r,1,n,1);
printf("%lld\n",ans);
}else if(p==2){
Update(l,(LL)r,1,n,1);
}
}
return 0;
}
void PushUp(int t)
{
sum[t]=sum[t<<1]+sum[t<<1|1];
dd[t]=dd[t<<1]+dd[t<<1|1];
}
void Build(int l,int r,int t)
{
if(l==r){
sum[t]=a[l];
dd[t]=d[l];
return;
}
int h=(l+r)>>1;
Build(l,h,t<<1);
Build(h+1,r,t<<1|1);
PushUp(t);
}
void Update(int id,LL C,int l,int r,int t)
{
if(l==r){
sum[t]=C;
dd[t]=C*(n-id+1);
return;
}
int h=(l+r)>>1;
if(h>=id) Update(id,C,l,h,t<<1);
else Update(id,C,h+1,r,t<<1|1);
PushUp(t);
}
LL Query1(int L,int R,int l,int r,int t)
{
if(L<=l&&R>=r) return dd[t];
int h=(l+r)>>1;
LL ans=0;
if(L<=h) ans+=Query1(L,R,l,h,t<<1);
if(R>h) ans+=Query1(L,R,h+1,r,t<<1|1);
return ans;
}
LL Query2(int L,int R,int l,int r,int t)
{
if(L<=l&&R>=r) return sum[t];
int h=(l+r)>>1;
LL ans=0;
if(L<=h) ans+=Query2(L,R,l,h,t<<1);
if(R>h) ans+=Query2(L,R,h+1,r,t<<1|1);
return ans;
}