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
题目来源
题意:
有长度为N的一个序列和M次操作。
操作1是计算a[l]×L+a[l+1]×(L−1)+⋯+a[r−1]×2+a[r]这个值,L是r-l+1这个长度。
操作2是把a[i]修改成另一个值。
思路:
用开两个树状数组,一个存a[i],另一个存(n-i+1)*a[i]。
当计算操作1时,用存(n-i+1)*a[i]的树状数组得到一个值减去存a[i]的树状数组的值,可以消去多余的系数。
当遇到操作2时,两个树状数组的值都要修改。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
ll tr[maxn][2];
ll a[maxn];
int lowbit(int i)
{
return i&(-i);
}
void add(int x,ll c,int op)
{
while(x<maxn)
{
tr[x][op]+=c;
x+=lowbit(x);
}
}
ll query(int x,int op)
{
ll ans=0;
while(x)
{
ans+=tr[x][op];
x-=lowbit(x);
}
return ans;
}
int main()
{
int n,q,op,l,r;
while(~scanf("%d%d",&n,&q))
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
{
add(i,a[i]*(n-i+1),1);
add(i,a[i],2);
}
for(int i=1;i<=q;i++)
{
scanf("%d%d%d",&op,&l,&r);
if(op&1)
{
printf("%lld\n",query(r,1)-query(l-1,1)-(query(r,2)-query(l-1,2))*(n-r));
}
else
{
add(l,-a[l]*(n-l+1),1);
add(l,-a[l],2);
a[l]=r;
add(l,a[l]*(n-l+1),1);
add(l,a[l],2);
}
}
}
return 0;
}