hdu 1754 I Hate It

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

這道題就是一道水題,求區間內的最大值

#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 300000
using namespace std;

int a[maxn];
int max2;
struct node
{
    int l,r,max1;
}tree[maxn*4];


void build(int i,int l,int r)
{
    tree[i].l=l;
    tree[i].r=r;
    if(l==r)
    {
        tree[i].max1=a[l];
        return;
    }
    int mid=(l+r)>>1;
    build(i<<1,l,mid);
    build(i<<1|1,mid+1,r);
    tree[i].max1=max(tree[i<<1].max1,tree[i<<1|1].max1);
}

void update(int i,int idx,int key)
{
    if(tree[i].l==tree[i].r)
    {
        tree[i].max1=key;
        return ;
    }
    int mid=(tree[i].l+tree[i].r)>>1;
    if(idx<=mid)
    {
         update(i<<1,idx,key);
    }
    else
        update(i<<1|1,idx,key);
    tree[i].max1=max(tree[i<<1].max1,tree[i<<1|1].max1);
}

void search1(int i,int l,int r)
{
    if(tree[i].l==l&&tree[i].r==r)
    {
        max2=max(max2,tree[i].max1);
        return ;
    }
    int mid=(tree[i].l+tree[i].r)>>1;
    if(r<=mid)
    {
        search1(i<<1,l,r);
    }
    else if(l>mid)
    {
        search1(i<<1|1,l,r);
    }
    else
    {
        search1(i<<1,l,mid);
        search1(i<<1|1,mid+1,r);
    }
}


int main()
{
    int N,M;
    while(scanf("%d%d",&N,&M)!=EOF)
    {
        for(int i=1; i<=N; i++)
        {
            scanf("%d",&a[i]);
        }
        getchar();
        build(1,1,N);
        for(int i=1; i<=M; i++)
        {
            char ch;
            int a,b;
            scanf("%c %d%d",&ch,&a,&b);
            getchar();
            if(ch=='Q')
            {
                max2=-1;
                search1(1,a,b);
                printf("%d\n",max2);
            }
            else if(ch=='U')
            {
                update(1,a,b);
            }
        }
    }
    return 0;
}


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