您的位置:首页 > 其它

poj3468 A Simple Problem with Integers(成段增减 区间求和)

2013-05-03 21:05 435 查看
成段增减 区间求和

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define lson l,m,rt<<1 //函数用左儿子
#define rson m+1,r,rt<<1|1 //函数用右儿子
#define havemid int m=(l+r)>>1 //取节点中点
#define left (rt<<1) //左儿子
#define right (rt<<1|1) //右儿子
#define LL long long
const int maxn= 100005; //最大节点个数
LL sum[maxn<<2]; //节点个数,开maxn的4倍
LL add[maxn<<2]; //lazy 标记
void pushup(int rt){
sum[rt]=sum[left]+sum[right];
}
void pushdown(int rt,int len){
if(add[rt]){
add[left]+=add[rt];
add[right]+=add[rt];
sum[left]+=add[rt]*(len-(len>>1));
sum[right]+=add[rt]*(len>>1);
add[rt]=0;
}
}
void build(int l,int r,int rt){
add[rt]=0;
if(l==r){
scanf("%lld",&sum[rt]);
return ;
}
havemid;
build(lson);
build(rson);
pushup(rt);
}
void update(int L,int R,int c,int l,int r,int rt){
if(L<=l&&r<=R){
add[rt]+=c;
sum[rt]+=(LL)c*(r-l+1);
return ;
}
pushdown(rt,r-l+1);
havemid;
if(L<=m)update(L,R,c,lson);
if(R>m)update(L,R,c,rson);
pushup(rt);
}
LL query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R){
return sum[rt];
}
pushdown(rt,r-l+1);
havemid;
LL ret=0;
if(L<=m)ret+=query(L,R,lson);
if(m<R)ret+=query(L,R,rson);
return ret;
}
char s[20];
int main()
{
int n,m,a,b,c;
while(scanf("%d%d",&n,&m)!=EOF)
{
build(1,n,1);
while(m--)
{
scanf("%s",s);
if(s[0]=='Q')
{
scanf("%d%d",&a,&b);
printf("%lld\n",query(a,b,1,n,1));
}
else {
scanf("%d%d%d",&a,&b,&c);
update(a,b,c,1,n,1);
}
}
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐