hdu1754线段树维护区间最大值

#include <iostream>
#include <cstdio>
using namespace std;


#define MAXN 200005

int N,M;

int grade[MAXN];

struct node
{
    int left;
    int right;
    int max;
}Tree[MAXN*20];



int Build(int start,int end,int root)
{
    Tree[root].left = start;
    Tree[root].right = end;

    if(start == end)
    {
        Tree[root].max = grade[start];
        return Tree[root].max;
    }

    int mid = (start + end)/2;

    int a = Build(start,mid,root*2);
    int b = Build(mid+1,end,(root*2)+1);

    return Tree[root].max = max(a,b);
}

int find(int start,int end,int root)
{
    if(start > Tree[root].right || end < Tree[root].left)
        return 0;

    if(start <= Tree[root].left && Tree[root].right <= end)
        return Tree[root].max;

    int a = find(start,end,root*2);
    int b = find(start,end,(root*2)+1);

    return max(a,b);
}


int update(int root,int pos,int value)
{
    if(pos < Tree[root].left || pos > Tree[root].right)
        return Tree[root].max;
    
    if(Tree[root].left == pos && Tree[root].right == pos)
        return Tree[root].max = value;

    int a = update(root*2,pos,value);
    int b = update((root*2)+1,pos,value);

    Tree[root].max = max(a,b);
    return Tree[root].max;
}

int main()
{
    while(scanf("%d%d",&N,&M)!=EOF)
    {
        for(int i = 1; i <= N; i++)
        {
            scanf("%d",&grade[i]);
        }
        Build(1,N,1);
        char ch;
        int A,B;
        while(M--)
        {
            getchar();
            scanf("%c%d%d",&ch,&A,&B);
            if(ch == 'Q')
                cout<<find(A,B,1)<<endl;
            else if(ch == 'U')
            {
                grade[A] = B;
                update(1,A,B);
            }
            
        }
    }
    return 0;
}


原文地址:https://www.cnblogs.com/javawebsoa/p/3236801.html