您的位置:首页 > 其它

[省选前题目整理][POJ 3468]A Simple Problem with Integers(线段树区间修改)

2015-04-11 15:40 218 查看

题目链接

http://poj.org/problem?id=3468

题目大意

要求对一个序列支持查询区间和、对给定区间中所有元素加同一值。

思路

经典的线段树区间修改、区间求和模板题。

代码

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>

#define MAXN 401000

using namespace std;

typedef long long int LL;

LL a[MAXN];
LL sum[MAXN],addtag[MAXN];

void pushup(int o)
{
sum[o]=sum[o<<1]+sum[o<<1|1];
}

void pushdown(int o,int L,int R)
{
if(addtag[o])
{
int M=(L+R)>>1;
addtag[o<<1]+=addtag[o];
addtag[o<<1|1]+=addtag[o];
sum[o<<1]+=(M-L+1)*addtag[o];
sum[o<<1|1]+=(R-M)*addtag[o];
addtag[o]=0;
}
}

void build(int o,int L,int R)
{
if(L==R)
{
sum[o]=a[L];
addtag[o]=0;
return;
}
LL M=(L+R)>>1;
build(o<<1,L,M);
build(o<<1|1,M+1,R);
pushup(o);
addtag[o]=0;
}

void update(int o,int L,int R,int ql,int qr,LL addv)
{
if(ql<=L&&R<=qr)
{
addtag[o]+=addv;
sum[o]+=(R-L+1)*addv; //!!!!!
return;
}
pushdown(o,L,R);
int M=(L+R)>>1;
if(ql<=M) update(o<<1,L,M,ql,qr,addv);
if(qr>M) update(o<<1|1,M+1,R,ql,qr,addv);
pushup(o);
}

LL query(int o,int L,int R,int ql,int qr)
{
if(ql<=L&&R<=qr)
return sum[o];
pushdown(o,L,R);
int M=(L+R)>>1;
LL ans=0;
if(ql<=M) ans+=query(o<<1,L,M,ql,qr);
if(qr>M) ans+=query(o<<1|1,M+1,R,ql,qr);
return ans;
}

int main()
{
int n,q;
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
build(1,1,n);
for(int i=1;i<=q;i++)
{
char cmd[4];
LL ql,qr,val;
scanf("%s%lld%lld",cmd,&ql,&qr);
if(cmd[0]=='C')
{
scanf("%lld",&val);
update(1,1,n,ql,qr,val);
}
else printf("%lld\n",query(1,1,n,ql,qr));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐