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

本文介绍了一种使用线段树实现区间更新和查询的基本方法,并通过懒惰传播优化性能。具体包括线段树的构建、更新及查询操作等核心代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本是裸的线段树,维护区间元素和,设一个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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值