您的位置:首页 > 其它

POJ 3468 A Simple Problem with Integers 线段树(成段更新)

2017-04-11 23:18 274 查看
基本是裸的线段树,维护区间元素和,设一个lazy数组来保存更新数据,区段更新即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<set>
#include<bitset>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#define INF 0x3f3f3f3f
#define inf 2*0x3f3f3f3f
#define llinf 1000000000000000000
#define pi acos(-1)
#define mod 1000000007
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
ll add[100005*4],sum[100005*4],t,n,q,x,y,z;
void pushup(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void pushdown(int rt,int m)
{
if (add[rt]) {
add[rt<<1] +=add[rt];add[rt<<1|1]+=add[rt];
sum[rt<<1] += (m - (m >> 1)) * add[rt];
sum[rt<<1|1] += (m >> 1) * add[rt];
add[rt] = 0;
}
}
void build(int l,int r,int rt)
{
add[rt]=0;
if(l==r)
{
scanf("%lld",&sum[rt]);
return ;
}
int m=(l+r)>>1;
build(lson);build(rson);
pushup(rt);
}
void Add(int L,int R,int x,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
add[rt]+=x;
sum[rt]+=(ll)x*(r-l+1);
return ;
}
pushdown(rt,r-l+1);
int m=(l+r)>>1;
if(L<=m)Add(L,R,x,lson);
if(R>m)Add(L,R,x,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);
int m=(l+r)>>1;
ll res=0;
if(L<=m)res+=query(L,R,lson);
if(R>m)res+=query(L,R,rson);
return res;
}
int main()
{
int n,q;
cin>>n>>q;
build(1,n,1);
while(q--)
{
char c;
int a,b,x;
scanf("\n%c%d%d",&c,&a,&b);
if(c=='Q')cout<<query(a,b,1,n,1)<<endl;
else
{
scanf("%d",&x);
Add(a,b,x,1,n,1);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐