HDOJ 1754 I Hate It 線段樹:單點替換 成求段最值

//HDOJ 1754 I Hate It  線段樹:單點替換 成求段最值
/*
題目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1754

題目大意:有n(0<n<=200000)個學生,已知每個學生的初始成績。
	有m(0<m<5000)次操作:	1、將a學生的成績改爲b;
				2、查詢區間[a,b]中成績最高的

思路:線段樹葉子結點記錄每個學生的成績,父親結點記錄其兩個子孩子中較高的成績,這樣根節點記錄的就是所有成績中最

高的。更新操作從根結點開始查找,一定在左孩子或右孩子其中一個,查詢後替換,然後往上更新父結點。查詢操作和敵兵布

陣一樣,直至記錄答案的時候不是累加結果,而是去更大的值,同樣遞歸實現,時間複雜度O(logn);
*/

#include <stdio.h>
#define root 1
#define MAXN 600000

int n,m,x,y,a[MAXN];
int Max(int a,int b){
    return a>b?a:b;
}
struct node
{
    int left;
    int right;
    int max;
}t[MAXN];

int build(int p,int left,int right)
{
    t[p].left = left;
    t[p].right = right;
    if (left == right)
         return t[p].max = a[left];
    int m=(left+right)/2;
    return t[p].max = Max(build(p*2, left, m),build(p*2+1, m+1, right));
}

int query(int p, int left ,int right)
{    
    if (t[p].left==left && t[p].right==right)
        return t[p].max;
    int m=(t[p].left+t[p].right)/2;
    if (right<=m)
        return query(p*2,left,right);
    if (left>m)
        return query(p*2+1,left,right);
    return Max(query(p*2,left,m),query(p*2+1,m+1,right));
}

void update(int p,int x,int y)
{
    if (t[p].left == t[p].right)
        t[p].max=y;
    else
    {
        int m = (t[p].left+t[p].right) / 2;
        if(x<=m){
            update(p*2,x,y);
            t[p].max=Max(t[p].max,t[p*2].max);
        }
        else{
            update(p*2+1,x,y);
            t[p].max=Max(t[p].max,t[p*2+1].max);
        }
    }
}
int main()
{
    int i;
    char c;
    while(scanf("%d %d",&n,&m)==2)
    {
        for(i=1;i<=n;i++)
            scanf("%d",&a[i]);
        getchar();
        build(root,1,n);
        while(m--){    
            scanf("%c %d %d",&c,&x,&y);
            getchar();
            if(c=='Q')
                printf("%d\n",query(root,x,y));
            else
                update(root,x,y);    
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章