学习日记:线段树基本操作

线段树(区间树)

oiwiki

题:洛谷P3372   (区间加,查询)

题:洛谷P3373     (区间加,乘,查询)

1.数组输入

2.建树(没啥特别注意的)

3.添加懒惰标记(如果没有全包含在修改区间内,则继续将懒惰标记下发给子结点)

4.查询(如果没有全包含在查询区间内,则继续将懒惰标记下发给子结点,并修改结点值)

自己写的基操代码,还不怎么熟练,应该还有些漏洞还没看出来(lazy长度为4n,n为数组长度)

#include <bits/stdc++.h>
#define int long long
using namespace std;
int arr[100005];
int lazy[400005];
int node[400005];
int n,m;
void build(int a,int b,int step)
{
    if(a==b){
        node[step]=arr[a];
        return ;
    }
    int m=(a+b)>>1;
    build(a,m,step*2);
    build(m+1,b,step*2+1);
    node[step]=node[step*2]+node[step*2+1];
}

void update(int a,int b,int l,int r,int step,int p)
{
    if( a<=l&&r<=b){
        lazy[step]+=p;
        node[step] += (r - l + 1) * p;
        return ;
    }
    int m=(l+r)>>1;
    if(lazy[step]&&l!=r){
        node[step*2]+=(m-l+1)*lazy[step];
        node[step*2+1]+=(r-m)*lazy[step];
        lazy[step*2]+=lazy[step];
        lazy[step*2+1]+=lazy[step];
        lazy[step]=0;
    }
    if(a<=m) update(a,b,l,m,step*2,p);
    if(b>m) update(a,b,m+1,r,step*2+1,p);
    node[step]=node[step*2]+node[step*2+1];
}

int query(int a,int b,int l,int r,int step)
{
    if(a<=l&&r<=b) return node[step];
    int m=(l+r)>>1;

    if(lazy[step]&&l!=r){
        node[step*2]+=(m-l+1)*lazy[step];
        node[step*2+1]+=(r-m)*lazy[step];
        lazy[step*2]+=lazy[step];
        lazy[step*2+1]+=lazy[step];
        lazy[step]=0;
    }
    int ans=0;
    if(a<=m) ans+=query(a,b,l,m,step*2);
    if(b>m) ans+=query(a,b,m+1,r,step*2+1);
    node[step]=node[step*2]+node[step*2+1];
    return ans;
}

signed main()
{


    cin >> n >> m;
    for(int i=1;i<=n;i++)
        cin >> arr[i] ;
        build(1,n,1);
    while(m--){
            int x;cin >> x;
        switch(x){
            case 1 :{
             int a,b,c;
             cin >> a >>b >>c;
             update(a,b,1,n,1,c);
             break;
            }
            case 2 :{
             int a,b;
             cin >> a >>b ;
             cout<<query(a,b,1,n,1)<<endl;
            }
        }
    }
}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值