线段树区间赋值+区间和查询

如题,代码如下:

#include<bits/stdc++.h>

using namespace std;

const int maxn=1e5+50;
const int maxNum=0x7fffffff-10;
struct node{
    int l,r,sum,lazy;
}tree[maxn<<2];

void build(int p,int l,int r)
{
    tree[p].l=l;
    tree[p].r=r;
    if(l==r){
        tree[p].sum=0,tree[p].lazy=-maxNum;   //注意要将标记设置为不可能作为区间赋值的数(同维护区间标记)
        return ;
    }
    int mid=(l+r)>>1;
    build(p<<1,l,mid);
    build(p<<1|1,mid+1,r);
    tree[p].sum=tree[p<<1].sum+tree[p<<1|1].sum;
}

void push_down(int p)
{
	if(tree[p].lazy!=-maxNum){
    tree[p<<1].lazy=tree[p<<1|1].lazy=tree[p].lazy;
    int mid=(tree[p].l+tree[p].r)>>1;
    tree[p<<1].sum=tree[p].lazy*(mid-tree[p].l+1);
    tree[p<<1|1].sum=tree[p].lazy*(tree[p].r-mid);
    tree[p].sum=tree[p].lazy*(tree[p].r-tree[p].l+1);
    tree[p].lazy=-maxNum;
    }
}

void update(int p,int l,int r,int v)
{
    if(tree[p].l>=l&&tree[p].r<=r){
        tree[p].lazy=v;
        tree[p].sum=(tree[p].r-tree[p].l+1)*tree[p].lazy;
        return ;
    }
    push_down(p);
    int mid=(tree[p].l+tree[p].r)>>1;
    if(l<=mid) update(p<<1,l,r,v);
    if(r>mid) update(p<<1|1,l,r,v);
    tree[p].sum=tree[p<<1].sum+tree[p<<1|1].sum;
}

int main()
{
    int n,q;
    scanf("%d%d",&n,&q);
    build(1,1,n),update(1,1,n,1);
    int x,y,z;
    for(int i=0;i<q;i++){
        scanf("%d%d%d",&x,&y,&z);
        update(1,x,y,z);
    }
    printf("The total value of the hook is %d.\n",tree[1].sum);
    return 0;
}

转载于原地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值