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).
将原式转化成:sum(1,l)+sum(1,l+1)+sum(1,l+2)....+sum(1,r)-(l-r+1)*sum(1,l-1)
用数组存储前缀和就可以
#include <iostream>
using namespace std;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define llson rt<<1
#define rrson rt<<1|1
#define ll long long
const int MAXN=1e5+50;
ll sum[MAXN],num[MAXN];
ll stree[MAXN<<2],lz_1[MAXN<<2];
void pushup(int l,int r,int rt)
{
int mid=(l+r)>>1;
stree[rt]=stree[llson]+(lz_1[llson]*(mid-l+1))+stree[rrson]+(lz_1[rrson]*(r-mid));
}
void build(int l,int r,int rt)
{
lz_1[rt]=0;
if(l==r)
{
stree[rt]=sum[l];
return;
}
int mid=(l+r)>>1;
build(lson);
build(rson);
pushup(l,r,rt);
}
void pushdown(int l,int r,int rt)
{
if(lz_1[rt])
{
int mid=(l+r)>>1;
lz_1[llson]+=lz_1[rt];
lz_1[rrson]+=lz_1[rt];
lz_1[rt]=0;
}
}
ll query(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
return stree[rt]+(lz_1[rt]*(r-l+1));
}
pushdown(l,r,rt);
int mid=(l+r)>>1;
ll ans=0;
if(L<=mid) ans+=query(L,R,lson);
if(R>mid) ans+=query(L,R,rson);
pushup(l,r,rt);
return ans;
}
void update(int L,int R,ll c,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
lz_1[rt]+=c;
return;
}
int mid=(l+r)>>1;
pushdown(l,r,rt);
if(L<=mid) update(L,R,c,lson);
if(R>mid) update(L,R,c,rson);
pushup(l,r,rt);
}
int main()
{
int n,q;
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
{
scanf("%lld",&num[i]);
sum[i]=sum[i-1]+num[i];
}
build(1,n,1);
for(int i=0;i<q;i++)
{
int k;
scanf("%d",&k);
if(k==1)
{
int a,b;
scanf("%d%d",&a,&b);
if(a>1)
printf("%lld\n",query(a,b,1,n,1)-(b-a+1)*query(a-1,a-1,1,n,1));
else
printf("%lld\n",query(a,b,1,n,1));
}
else
{
int a,b;
scanf("%d%d",&a,&b);
update(a,n,b-num[a],1,n,1);
num[a]=b;
}
}
return 0;
}