HDU1754(單點更新線段樹)

手撕代碼的問題基本解決,但是總是在做題時出現細節性失誤,引以爲戒,引以爲戒。。。
另外,修改區間內的值而不是加減,必須更新到每一個點。
此處有別的問題可以加深一下
code:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

const int maxn=200100;
const int inf=0x3f3f3f3f;

int maxtree[maxn<<2];

void pushUp(int rt)
{
    maxtree[rt]=max(maxtree[rt<<1],maxtree[rt<<1|1]);
}

void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&maxtree[rt]);
        return ;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    pushUp(rt);
}

void update(int p,int add,int l,int r,int rt)
{
    if(l==r)
    {
        maxtree[rt]=add;
        return ;
    }
    int m=(l+r)>>1;
    if(p<=m)
    {
        update(p,add,lson);
    }
    else
    {
        update(p,add,rson);
    }
    pushUp(rt);
}

int query(int L,int R,int l,int r,int rt)
{
    int maxx=-inf;
    if(l>=L&&r<=R)
    {
        return maxtree[rt];
    }
    int m=(l+r)>>1;
    if(L<=m)
        maxx=max(maxx,query(L,R,lson));
    if(R>m)
        maxx=max(maxx,query(L,R,rson));
    return maxx;
}

int main()
{
    int n,m;
    char s[5];
    int a,b;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        build(1,n,1);
        while(m--)
        {
            scanf("%s",s);
            scanf("%d%d",&a,&b);
            if(s[0]=='Q')
                printf("%d\n",query(a,b,1,n,1));
            if(s[0]=='U')
                update(a,b,1,n,1);
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章