HDU 1754 I Hate It 线段树 RMQ 支持修改数列的值

//http://acm.hdu.edu.cn/showproblem.php?pid=1754
//4671581 2011-09-28 14:15:02 Accepted 1754 265MS 6452K 2127 B G++ nkhelloworld
//4671584 2011-09-28 14:15:21 Accepted 1754 218MS 6388K 2127 B C++ nkhelloworld

//以下是未加输入优化的测试结果,对比发现效率提升很大
//4671535 2011-09-28 14:08:36 Accepted 1754 1109MS 6444K 2029 B G++ nkhelloworld
//4671539 2011-09-28 14:09:20 Accepted 1754 515MS 6388K 2029 B C++ nkhelloworld
#include <cstdio>
#include <iostream>
using namespace std;
#define MAXN 200000
struct SEGMENTTREE
{
    int left,right,maxval;
}tree[MAXN*4+1];
int n,m;

char ch;
inline void readint(int &x)
{
    while(ch = getchar(),ch < '0' || ch > '9');
    x = ch - '0';
    while(ch = getchar(),ch >='0' && ch <='9')  x = x * 10 + ch - '0';
}

void buildsegtree(int pos,int left,int right)
{
    tree[pos].left = left;  tree[pos].right = right;
    if(left==right)
    {
        readint(tree[pos].maxval);
        return ;
    }
    int mid = (left+right)>>1;
    buildsegtree(pos<<1,left,mid);
    buildsegtree(pos<<1|1,mid+1,right);
    tree[pos].maxval = max(tree[pos<<1].maxval,tree[pos<<1|1].maxval);
}

void update(int root,int updatepos,int num)
{
    if(tree[root].left == tree[root].right)
    {
        tree[root].maxval = num;
        return ;
    }
    int mid = (tree[root].left + tree[root].right)>>1;
    if(updatepos <=mid)
        update(root<<1,updatepos,num);
    else
        update(root<<1|1,updatepos,num);
    tree[root].maxval = max( tree[root<<1].maxval , tree[root<<1|1].maxval );
}

int query(int root,int a,int b)
{
    if(tree[root].left == a && tree[root].right == b)
        return tree[root].maxval;
    int mid = (tree[root].left+tree[root].right)>>1;
    if(a > mid)
        return query(root<<1|1,a,b);
    else if(b <= mid)
        return query(root<<1,a,b);
    return max(query(root<<1,a,mid) , query(root<<1|1,mid+1,b));
}



int main()
{
    int i,j,a,b;
    char op[5];
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        buildsegtree(1,1,n);
        for(i=1;i<=m;i++)
        {
            scanf("%s",op);
            if(op[0] == 'Q')
            {
                readint(a); readint(b);
                if(a>b) swap(a,b);
                printf("%d\n",query(1,a,b));
            }
            else
            {
                readint(a); readint(b);
                update(1,a,b);
            }
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/nkhelloworld/archive/2011/09/28/2194219.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值