您的位置:首页 > 其它

3212: Pku3468 A Simple Problem with Integers

2018-04-09 21:12 337 查看
题目链接

题目大意:线段树区间求和,区间查询

题解:我为什么要看这样的题……

我的收获:手速++

#include <iostream>
#include <cstdio>
using namespace std;

#define M 100005
#define ls x<<1
#define rs x<<1|1
#define lson l,m,ls
#define rson m+1,r,rs
#define root 1,n,1

int n,m,x,y,z,a[M];
long long sum[M<<2],add[M<<2];

inline void pushup(int x){sum[x]=sum[ls]+sum[rs];}

void pushdown(int x,int m)
{
if(!add[x]) return ;
add[ls]+=add[x];
add[rs]+=add[x];
sum[ls]+=add[x]*(m-(m>>1));
sum[rs]+=add[x]*(m>>1);
add[x]=0;
}

void build(int l,int r,int x)
{
add[x]=0;
if(l==r) {sum[x]=a[l];return ;}
int m=(l+r)>>1;
build(lson),build(rson);
pushup(x);
}

void updata(int L,int R,int p,int l,int r,int x)
{
if(L<=l&&r<=R) {add[x]+=p,sum[x]+=p*(r-l+1);return ;}
pushdown(x,r-l+1);
int m=(l+r)>>1;
if(L<=m) updata(L,R,p,lson);
if(R>m) updata(L,R,p,rson);
pushup(x);
}

long long query(int L,int R,int l,int r,int x)
{
if(L<=l&&r<=R) return sum[x];
pushdown(x,r-l+1);
int m=(l+r)>>1;long long ans=0;
if(L<=m) ans+=query(L,R,lson);
if(R>m) ans+=query(L,R,rson);
return ans;
}

void work()
{
char opt[10];
while(m--)
{
scanf("%s%d%d",opt,&x,&y);
if(opt[0]=='Q') printf("%lld\n",query(x,y,root));
else{scanf("%d",&z),updata(x,y,z,root);}
}
}

void init()
{
cin>>n>>m;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
build(root);
}

int main()
{
init();
work();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: