HDU 1754:I Hate It

点击打开题目链接

线段树入门题目,单点更改,区间查询。

AC代码:

#include<iostream>
#include<stdio.h>
#include<algorithm>
#define lchild left,mid,root<<1
#define rchild mid+1,right,root<<1|1

using namespace std;

const int maxn = 200020;
int max_sc[maxn<<2];
//更新当前节点
void push_up(int root)
{
    max_sc[root] = max(max_sc[root<<1],max_sc[root<<1|1]);
}
//构建线段树
void build(int left,int right,int root)
{
    if(left == right)
    {
        scanf("%d",&max_sc[root]);
        return;
    }
    int mid = (left+right)>>1;
    build(lchild);
    build(rchild);
    push_up(root);
}
void update(int left,int right,int root,int a,int b)
{
    if(left == right)
    {
        max_sc[root] = b;
        return;
    }
    int mid = (left+right)>>1;
    if(a<=mid) update(lchild,a,b);
    else update(rchild,a,b);
    push_up(root);
}
int Query(int left,int right,int root,int a,int b)
{
    if(a<=left && right<=b)
    {
        return max_sc[root];
    }
    int mid = (left+right)>>1;
    int ans = 0;
    if(a<=mid) ans = max(ans,Query(lchild,a,b));
    if(b>mid) ans = max(ans,Query(rchild,a,b));
    return ans;
}
int main()
{
    int n,m,a,b;
    char op;
    while(~scanf("%d%d",&n,&m))
    {
        build(1,n,1);
        while(m--)
        {
            //注意吞空格的问题。
            scanf(" %c %d%d",&op,&a,&b);
            if(op == 'Q')
            {
                int ans = Query(1,n,1,a,b);
                printf("%d\n",ans);
            }
            else
            {
                update(1,n,1,a,b);
            }
        }
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值