2016夏季练习——线段树

本文介绍了一种使用懒惰标记优化的线段树数据结构实现,并通过一个具体实例展示了其构建、更新及查询的过程。该算法适用于解决区间更新与查询的问题。

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

来源:HDU1698

lazy标记的线段树

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#define lch (rt<<1)
#define rch (rt<<1|1)
using namespace std;
const int MAXN = 100000+10;
int tree[MAXN*4];
int lazy[MAXN*4];
int n;
int Q;
int x,y,v;
void pushup(int rt){
    tree[rt]=tree[lch]+tree[rch];
    return ;
}
void pushdown(int rt,int d){
    //cout<<rt<<" "<<d<<endl;
    if(lazy[rt]){
        lazy[lch]=lazy[rt];
        lazy[rch]=lazy[rt];
        tree[lch]=lazy[rt]*(d-(d>>1));
        tree[rch]=lazy[rt]*(d>>1);
        lazy[rt]=0;
    }
}
void build(int rt,int left,int right){
    tree[rt]=1;
    lazy[rt]=0;
    if(left==right){
        return ;
    }
    int mid=(left+right)>>1;
    build(lch,left,mid);
    build(rch,mid+1,right);
    pushup(rt);
}
void update(int rt,int left,int right,int l,int r,int data){
    if(left>=l&&r>=right){
        lazy[rt]=data;
        tree[rt]=(right-left+1)*data;
        return ;
    }
    pushdown(rt,right-left+1);
    int mid=(left+right)>>1;
    if(l<=mid) update(lch,left,mid,l,r,data);
    if(r>mid) update(rch,mid+1,right,l,r,data);
    pushup(rt);
}
int main(){
	int T,nc=1;
	scanf("%d",&T);
	while(T--){
        scanf("%d",&n);
        scanf("%d",&Q);
        memset(tree,0,sizeof(tree));
        memset(lazy,0,sizeof(lazy));
        build(1,1,n);
        for(int i=0;i<Q;i++){
            scanf("%d%d%d",&x,&y,&v);
            update(1,1,n,x,y,v);
            //cout<<tree[1]<<endl;
        }
        cout<<"Case "<<nc++<<": The total value of the hook is "<<tree[1]<<"."<<endl;//注意最后一个句号
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值