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].
Unfortunately, the longer he learns, the fewer he gets.
That means, if he reads books from l to r, he will get
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).
Now Ryuji has qq questions, you should answer him:
1. If the question type is 1, you should answer how much knowledge he will get after he reads books [ l, r ].
2. If the question type is 2, Ryuji will change the ith book's knowledge to a new value.
Input
First line contains two integers nn and qq (n,q≤100000).
The next line contains n integers represent a[i](a[i]≤1e9) .
Then in next qq line each line contains three integers a, b, c, if a=1, it means question type is 1, and bb, ccrepresents [ l , r ]. if a = 2 , it means question type is 2 , and bb, c means Ryuji changes the bth book' knowledge to c
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[i]*r-i+1=a[i]*(n-i+1)-a[i]*(n-r),即可化简公式:
画图即可看出就是求两个前缀和。这里我用树状数组进行求前缀和。当然也可以用线段树。
#include<bits/stdc++.h>
using namespace std;
#define e exp(1)
#define pi acos(-1)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define ll long long
#define ull unsigned long long
#define mem(a,b) memset(a,b,sizeof(a))
int gcd(int a,int b){return b?gcd(b,a%b):a;}
const int maxn=1e6+5;
int n,q;
ll a[maxn];
ll c1[maxn],c2[maxn];
int lowbit(int x)
{
return x&(-x);
}
void add1(int i,ll value)
{
while(i<=n)
{
c1[i]+=value;
i+=lowbit(i);
}
}
void add2(int i,ll value)
{
while(i<=n)
{
c2[i]+=value;
i+=lowbit(i);
}
}
ll getsum1(int i)
{
ll ans=0;
while(i>0)
{
ans+=c1[i];
i-=lowbit(i);
}
return ans;
}
ll getsum2(int i)
{
ll ans=0;
while(i>0)
{
ans+=c2[i];
i-=lowbit(i);
}
return ans;
}
int main()
{
while(~scanf("%d%d",&n,&q))
{
mem(c1,0);mem(c2,0);
for(int i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
add1(i,a[i]*(n-i+1));
add2(i,a[i]);
}
while(q--)
{
int op,x,y;scanf("%d%d%d",&op,&x,&y);
if(op==1)
{
ll ans=getsum1(y)-getsum1(x-1);
ans-=(getsum2(y)-getsum2(x-1))*(n-y);
printf("%lld\n",ans);
}
else
{
add1(x,(n-x+1)*(y-a[x]));
add2(x,y-a[x]);
a[x]=y;
}
}
}
return 0;
}