地址:http://poj.org/problem?id=3468
思路:区间线段树模板题。。
Code:
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
const int MAX_N=1e5+5;
struct tree{
int l,r;
LL lazy;
LL x;
int mid(){
return (l+r)>>1;
}
};
int n,Q;
int a[MAX_N];
tree Tree[MAX_N<<2];
void PushUp(int rt);
void PushDown(int rt);
void Build(int l,int r,int rt);
void Update(int l,int r,LL x,int rt);
LL Query(int l,int r,int rt);
int main()
{
scanf("%d%d",&n,&Q);
for(int i=1;i<=n;++i)
scanf("%d",&a[i]);
Build(1,n,1);
char ch[5];
int l,r,x;
while(Q--){
scanf("%s%d%d",ch,&l,&r);
if(ch[0]=='C'){
scanf("%d",&x);
Update(l,r,x,1);
}else{
printf("%lld\n",Query(l,r,1));
}
}
return 0;
}
void PushUp(int rt)
{
Tree[rt].x=Tree[rt<<1].x+Tree[(rt<<1)|1].x;
}
void PushDown(int rt)
{
if(Tree[rt].lazy){
int h=Tree[rt].r-Tree[rt].l+1;
Tree[rt<<1].lazy+=Tree[rt].lazy;
Tree[(rt<<1)|1].lazy+=Tree[rt].lazy;
Tree[rt<<1].x+=Tree[rt].lazy*(h-(h>>1));
Tree[(rt<<1)|1].x+=Tree[rt].lazy*(h>>1);
Tree[rt].lazy=0;
}
}
void Build(int l,int r,int rt)
{
Tree[rt].l=l; Tree[rt].r=r;
if(l==r){
Tree[rt].x=a[l]; return;
}
int h=(l+r)>>1;
Build(l,h,rt<<1);
Build(h+1,r,(rt<<1)|1);
PushUp(rt);
}
void Update(int l,int r,LL x,int rt)
{
if(l<=Tree[rt].l&&r>=Tree[rt].r){
Tree[rt].lazy+=x;
Tree[rt].x+=(Tree[rt].r-Tree[rt].l+1)*x;
return;
}
PushDown(rt);
int H=Tree[rt].mid();
if(H>=l) Update(l,r,x,rt<<1);
if(H<r) Update(l,r,x,(rt<<1)|1);
PushUp(rt);
}
LL Query(int l,int r,int rt)
{
if(l<=Tree[rt].l&&r>=Tree[rt].r) return Tree[rt].x;
PushDown(rt);
LL res=0;
int H=Tree[rt].mid();
if(H>=l) res+=Query(l,r,rt<<1);
if(H<r) res+=Query(l,r,(rt<<1)|1);
return res;
}