HDU - 1754 I Hate It (线段树区间最值)

题意:给出N个数,并且有修改第i个数的值,和查询在某个区间的最大值

思路:使用线段树来记录区间的最值,此题还是仅仅对叶子结点的修改,所以即 在HDU-1166 上把 update 和 query 函数进行略微修改即可。

 

完整代码:


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=200005;
int s[maxn],seg[maxn<<2];

void push_up(int rt)
{
    seg[rt]=max(seg[rt<<1],seg[rt<<1|1]);   //求最大值
}
void build(int l,int r,int rt)
{
    if(l==r)
    {
        seg[rt]=s[l];
        return ;
    }
    int mid=(l+r)/2;
    build(l,mid,rt<<1);
    build(mid+1,r,rt<<1|1);
    push_up(rt);
}
int query(int L,int R,int l,int r,int rt)
{
    if(L<=l && R>=r) return seg[rt];
    int mid=(l+r)>>1;
    int ret=0;
    if(L<=mid)  ret=max(ret,query(L,R,l,mid,rt<<1));
    if(R>mid)   ret=max(ret,query(L,R,mid+1,r,rt<<1|1));
    return ret;
}
void update(int L,int s,int l,int r,int rt)
{
    if(l==r)
    {
        seg[rt]=s;
        return ;
    }
    int mid=(l+r)>>1;
    if(L<=mid)  update(L,s,l,mid,rt<<1);
    else     update(L,s,mid+1,r,rt<<1|1);
    push_up(rt);
}
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=1; i<=n; i++)  
      scanf("%d",&s[i]); build(1,n,1); int a,b; char ch; while(m--) { scanf(" %c%d%d",&ch,&a,&b); if(ch=='Q') printf("%d\n",query(a,b,1,n,1)); else update(a,b,1,n,1); } } return 0; }
 

 

posted @ 2019-07-24 16:16  Tianwell  阅读(168)  评论(0编辑  收藏  举报