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

链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1754



分析与总结:

线段树求区间最大值,好像也没什么可讲的。


代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define lson(x) (x<<1)
#define rson(x) (lson(x)|1)
using namespace std;

typedef int Type;
const int MAX_NODE = 200005<<2;

struct node{
    int left, right;
    Type val;
    int mid(){return (left+right)>>1;}
    bool buttom(){return left==right;}
};

class SegTree{
public:
    void build(int cur,int left,int right){
        t[cur].left  = left;
        t[cur].right = right;
        if(left == right){
            scanf("%d",&t[cur].val);
            return;
        }
        int m = t[cur].mid();
        build(lson(cur),left,m);
        build(rson(cur),m+1,right);
        push_up(cur);
    }
    void update(int cur,int p,int data){
        if(t[cur].buttom()){
            t[cur].val = data;
            return;
        }
        int m = t[cur].mid();
        if(p <= m)
            update(lson(cur),p,data);
        else
            update(rson(cur),p,data);
        push_up(cur);
    }
    int query(int cur,int left,int right){
        if(t[cur].left==left && t[cur].right==right){
            return t[cur].val;
        }
        int m = t[cur].mid();
        if(right <= m)
            return query(lson(cur),left,right);
        else if(left > m)
            return query(rson(cur),left,right);
        else
            return max(query(lson(cur),left,m), query(rson(cur),m+1,right));
    }

private:
    void push_up(int cur){
        t[cur].val = max(t[lson(cur)].val,t[rson(cur)].val);
    }
private:
    node t[MAX_NODE];
};

SegTree st;

int main(){
    int n,m,x,y;
    char cmd[5];
    while(~scanf("%d%d",&n,&m)){
        st.build(1,1,n);
        for(int i=0; i<m; ++i){
            scanf("%s %d %d",cmd,&x,&y);
            if(cmd[0] == 'Q') printf("%d\n", st.query(1,x,y));
            else st.update(1,x,y);
        }
    }
    return 0;
}


—— 生命的意义,在于赋予它意义士。

原创http://blog.csdn.net/shuangde800By D_Double (转载请标明)



你可能感兴趣的:(HDU)