线段树基础题,加上一个lazy标记,裸线段数随便过,就当是复习模板了。。。一开始忘了把标记变量也开成long long 结果wa了一炮。。。水题更要小心
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
struct rec{int l,r,lch,rch; long long sum,biao;}tree[4001000];
int tot=0,a[200100],n,q;
void updata(int x)
{
if (tree[x].lch!=0)
{
tree[tree[x].lch].biao+=tree[x].biao;
tree[tree[x].lch].sum+=tree[x].biao*(tree[tree[x].lch].r-tree[tree[x].lch].l+1);
}
if (tree[x].rch!=0)
{
tree[tree[x].rch].biao+=tree[x].biao;
tree[tree[x].rch].sum+=tree[x].biao*(tree[tree[x].rch].r-tree[tree[x].rch].l+1);
}
tree[x].biao=0;
}
void maketree(int l,int r)
{
int now=++tot;
tree[now].l=l,tree[now].r=r;
if (l==r) return ;
int mid=(l+r)>>1;
tree[now].lch=tot+1;maketree(l,mid);
tree[now].rch=tot+1;maketree(mid+1,r);
}
void insert(int x,int l,int r,int w)
{
updata(x);
if (tree[x].l>=l&&tree[x].r<=r)
{
tree[x].sum+=(tree[x].r-tree[x].l+1)*w;
tree[x].biao+=w;
return;
}
int mid=(tree[x].l+tree[x].r)>>1;
if (l<=mid) insert(tree[x].lch,l,r,w);
if (r>mid) insert(tree[x].rch,l,r,w);
tree[x].sum=tree[tree[x].lch].sum+tree[tree[x].rch].sum;
}
long long getsum(int x,int l,int r)
{
long long now=0;
updata(x);
if (tree[x].l>=l&&tree[x].r<=r)
return tree[x].sum;
int mid=(tree[x].l+tree[x].r)>>1;
if (l<=mid) now+=getsum(tree[x].lch,l,r);
if (r>mid) now+=getsum(tree[x].rch,l,r);
return now;
}
int main()
{
int i,x,y,w;
char ch;
memset(tree,0,sizeof(tree));
scanf("%d %d",&n,&q);
maketree(1,n);
for (i=1;i<=n;i++)
{
scanf("%d",&a[i]);
insert(1,i,i,a[i]);
}
for (i=1;i<=q;i++)
{
scanf(" %c ",&ch);
if (ch=='Q')
{
scanf("%d %d",&x,&y);
printf("%lld\n",getsum(1,x,y));
}
if (ch=='C')
{
scanf("%d %d %d",&x,&y,&w);
insert(1,x,y,w);
}
}
}