hdu 1698 Just a Hook 线段树成段更新

本文介绍了一种基于树状数组实现的区间更新查询算法,该算法能够在对数时间内完成区间元素的批量更新及查询操作。通过定义树状数组结构,并实现pushup、pushdown、build、update和query等关键函数,确保了对于复杂的数据集也能高效地处理区间内的数值变化。

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

裸的成段更新。。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define maxn 110000
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
int tree[maxn<<2],lazy[maxn<<2];
void pushup(int rt)
{
    tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
void pushdown(int rt,int mid)
{
    if(lazy[rt])
    {
        lazy[rt<<1]=lazy[rt<<1|1]=lazy[rt];
        tree[rt<<1]=lazy[rt]*(mid-(mid>>1));
        tree[rt<<1|1]=lazy[rt]*(mid>>1);
        lazy[rt]=0;
    }
}
void build(int rt,int l,int r)
{
    int m=(l+r)>>1;
    lazy[rt]=0;
    if(l==r)
    {
        tree[rt]=1;
        return;
    }
    build(lson);
    build(rson);
    pushup(rt);
}
void update(int rt,int l,int r,int x,int y,int val)
{
    if(x<=l&&r<=y)
    {
        lazy[rt]=val;
        tree[rt]=val*(r-l+1);
        return;
    }
    pushdown(rt,r-l+1);
    int m=(l+r)>>1;
    if(x<=m)
    {
        update(lson,x,y,val);
    }
    if(y>m)
    {
        update(rson,x,y,val);
    }
    pushup(rt);
}
int query(int rt,int l,int r,int x,int y)
{
    if(x==l&&y==r)
    {
        return tree[rt];
    }
    pushdown(rt,r-l+1);
    int m=(l+r)>>1;
    int tmp=0;
    if(y<=m)
    {
        return query(lson,x,y);
    }
    else if(x>m)
    {
        return query(rson,x,y);
    }
    else
    {
        return query(lson,x,m)+query(rson,m+1,y);
    }

}
int main()
{
    int cas=0,n,m,t;
    int a,b,c;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        build(1,1,n);
        scanf("%d",&m);
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d%d",&a,&b,&c);
            update(1,1,n,a,b,c);
        }
        int ans=query(1,1,n,1,n);
        cas++;
        printf("Case %d: The total value of the hook is %d.\n",cas,ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值