关于线段树,强烈推荐HH的博客 www.notonlysuccess.com 里面的线段树完全版
POJ3468 典型的区间更新,有一个延迟标记,如果所求的区间包含这个有延迟标记的区间,直接返回,不需要遍历到叶子节点,pushdown函数将延迟标记传递给子节点
这题要注意用LONG LONG
#include<stdio.h>
#include<string.h>
#define LL long long
#define maxn 100010
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
struct node
{
int l,r;
LL sum;
LL flag;
}tree[300010];
int a[maxn];
void pushup(int rt)
{
tree[rt].sum=tree[rt<<1].sum+tree[rt<<1|1].sum;
}
void pushdown(int rt)
{
if(tree[rt].flag)
{
tree[rt<<1].flag+=tree[rt].flag;
tree[rt<<1|1].flag+=tree[rt].flag;
tree[rt<<1].sum+=tree[rt].flag*(tree[rt<<1].r-tree[rt<<1].l+1);
tree[rt<<1|1].sum+=tree[rt].flag*(tree[rt<<1|1].r-tree[rt<<1|1].l+1);
tree[rt].flag=0;
}
}
void build(int rt,int l,int r)
{
tree[rt].l=l;
tree[rt].r=r;
tree[rt].flag=0;
if(l==r)
{
tree[rt].sum=a[l];
return ;
}
int mid=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
void update(int rt,int L,int R,int c)
{
if(L<=tree[rt].l&&tree[rt].r<=R)
{
tree[rt].flag+=c;
tree[rt].sum+=(LL)c*(tree[rt].r-tree[rt].l+1);
return ;
}
pushdown(rt);
int mid=(tree[rt].l+tree[rt].r)>>1;
if(L<=mid)
update(rt<<1,L,R,c);
if(R>mid)
update(rt<<1|1,L,R,c);
pushup(rt);
}
LL query(int rt,int L,int R)
{
if(L<=tree[rt].l&&tree[rt].r<=R)
return tree[rt].sum;
pushdown(rt);
int mid=(tree[rt].r+tree[rt].l)>>1;
LL ans=0;
if(L<=mid)
ans+=query(rt<<1,L,R);
if(R>mid)
ans+=query(rt<<1|1,L,R);
return ans;
}
int main()
{
int n,q;
while(scanf("%d%d",&n,&q)==2)
{
int i;
for(i=1;i<=n;i++)
scanf("%lld",&a[i]);
build(1,1,n);
char ch;
int x,y,z;
while(q--)
{
getchar();
scanf("%c",&ch);
if(ch=='Q')
{
scanf("%d%d",&x,&y);
printf("%lld\n",query(1,x,y));
}
else if(ch=='C')
{
scanf("%d%d%d",&x,&y,&z);
update(1,x,y,z);
}
}
}
return 0;
}