HDU 6315 Naive Operations【线段树】

本文介绍了一种使用线段树解决特定区间查询问题的方法。对于给定的数组b和一系列操作,包括区间加一(add)和区间查询(query),通过维护线段树中的和值与最小值来高效地完成任务。

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

题目链接

题目意思

初始a数组为0,给你一个b数组,q次询问add x y为a数组区间x y增加1,query x y查询区间x~y中a[i]/b[i]向下取正的和值。

解题思路

区间查询问题,我们首先想到的就是线段树。
我们用sum数组去维护区间的和值,由于分母是固定的,那么就维护一个数组sub[root]=min(b[i]-a[i]%b[i])的值。这样如果sub[root]=0,那么我们就下推懒惰标记,同时更新区间的值。

代码部分
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <algorithm>
#define lchild left,mid,root<<1
#define rchild mid+1,right,root<<1|1
using namespace std;
typedef long long ll;
const int maxn=1e5+10;
int b[maxn];
int sub[maxn<<2],sum[maxn<<2],lazy[maxn<<2];
///更新线段树节点
void push_up(int root)
{
    sum[root]=sum[root<<1]+sum[root<<1|1];
    sub[root]=min(sub[root<<1],sub[root<<1|1]);
}
///懒惰标记下推
void push_down(int root)
{
    lazy[root<<1]+=lazy[root];
    sub[root<<1]-=lazy[root];
    lazy[root<<1|1]+=lazy[root];
    sub[root<<1|1]-=lazy[root];
    lazy[root]=0;
}
///构建线段树
void build(int left,int right,int root)
{
    sum[root]=0;
    lazy[root]=0;
    if(left==right)
    {
        scanf("%d",&b[left]);
        sub[root]=b[left];
        return;
    }
    int mid=(left+right)>>1;
    build(lchild);
    build(rchild);
    push_up(root);
}
void update1(int left,int right,int root)
{
    if(left==right)
    {
        sum[root]++;
        sub[root]=b[left];
        return ;
    }
    int mid=(left+right)>>1;
    push_down(root);
    if(!sub[root<<1])
        update1(lchild);
    if(!sub[root<<1|1])
        update1(rchild);
    push_up(root);
}
///更新操作
void update(int a,int b,int left,int right,int root)
{
    if(left>=a&&right<=b)
    {
        lazy[root]++;
        sub[root]--;
        if(!sub[root])
            update1(left,right,root);
        return;
    }
    int mid=(left+right)>>1;
    push_down(root);
    if(a<=mid)
        update(a,b,lchild);
    if(b>mid)
        update(a,b,rchild);
    push_up(root);
}
///查询操作
int query(int a,int b,int left,int right,int root)
{
    if(left>=a&&right<=b)
    {
        return sum[root];
    }
    int ans=0;
    int mid=(left+right)>>1;
    push_down(root);
    if(a<=mid)
        ans+=query(a,b,lchild);
    if(b>mid)
        ans+=query(a,b,rchild);
    push_up(root);
    return ans;
}
int main()
{
    int n,q;
    while(scanf("%d%d",&n,&q)!=EOF)
    {
        build(1,n,1);
        char s[10];
        int a,b;
        while(q--)
        {
            scanf("%s%d%d",s,&a,&b);
            if(s[0]=='a')
                update(a,b,1,n,1);
            else
                printf("%d\n",query(a,b,1,n,1));
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值