题意:
查询:【l,r】数列的和
修改:【l,r】数列的值+=c
思路:
查询:维护区间加法和sum
修改:维护修改叠加标记lazy
注意:ll
C++ 1750ms G++2650ms
难度:0.6
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
#define ll long long
const int inf=0x3f3f3f;
struct Stree
{
ll val;
ll lazy;
} sts[4*100005]; //开4倍
ll a[100005];
void pushup(int root)
{
sts[root].val=sts[root<<1].val+sts[root<<1|1].val;
}
void pushdown(int root,int numl,int numr)
{
if(sts[root].lazy!=0)
{
sts[root<<1].lazy+=sts[root].lazy;
sts[root<<1|1].lazy+=sts[root].lazy;
sts[root<<1].val+=sts[root].lazy*numl;
sts[root<<1|1].val+=sts[root].lazy*numr;
sts[root].lazy=0;
}
}
void build(int l,int r,int root)//根节点从1开始吧
{
if(l==r)//到达子节点
{
sts[root].val=a[l];
}
else
{
sts[root].val=sts[root].lazy=0;//没了这句会WA,清空lazy跟val
int mid=(l+r)>>1;//(l+r)/2
build(l,mid,root<<1);
build(mid+1,r,root<<1|1);
pushup(root);//更新本节点
}
}
ll query(int nowl,int nowr,int ql,int qr,int root)
{
if(nowl>=ql&&nowr<=qr)
{
return sts[root].val;
}
int mid=(nowl+nowr)>>1;
pushdown(root,mid-nowl+1,nowr-mid);
ll ans=0;
if(ql<=mid)ans+=query(nowl,mid,ql,qr,root<<1);
if(qr>mid)ans+=query(mid+1,nowr,ql,qr,root<<1|1);
return ans;
}
void update(int nowl,int nowr,int ul,int ur,int root,ll addval)//nowl,nowr 当前区间 ul,ur 需修改的区间
{
int mid=(nowl+nowr)>>1;
if(ul<=nowl&&ur>=nowr)//当前区间是修改区间的子区间
{
sts[root].val+=1ll*addval*(nowr-nowl+1);
sts[root].lazy+=addval;
return ;
}
pushdown(root,mid-nowl+1,nowr-mid);
if(ul<=mid) update(nowl,mid,ul,ur,root<<1,addval);//左子树与修改区间有交集
if(ur>mid) update(mid+1,nowr,ul,ur,root<<1|1,addval);
pushup(root);
}
void op(int n);
int main()
{
int n,m;
cin>>n>>m;char cc[5];
for(int i=1; i<=n; i++)
scanf("%lld",&a[i]);
build(1,n,1);
//op(n);
int l,r; ll c;
for(int i=1;i<=m;i++)
{
scanf("%s",&cc);
if(cc[0]=='C')
{
scanf("%d %d %lld",&l,&r,&c);
update(1,n,l,r,1,c);
}
else
{
scanf("%d %d",&l,&r);
printf("%lld\n",query(1,n,l,r,1));
}
}
}
void op(int n)
{
printf("\n///\n");
int up=pow(2.0,ceil(log10((double)n)/log10(2.0))+1)-1;
for(int i=1; i<=up; i++)
{
printf("%d ",sts[i].val);
int t=log10((double)i+1.0)/log10(2.0);
if(pow(2.0,t)==i+1)
printf("\n");
}
printf("///\n");
}