vijos1514 天才的記憶 線段樹

題解:題目意思很明確,就是查詢串的區間最值,利用線段樹可以便捷的解出。要注意的是在query查詢的時候,初始值ret最好是設爲大負數比如-(1<<30).因爲題目的測試數據很有可能是有很大的負數存在的。

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<queue>
#define maxn 200002
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int a[maxn<<2];
void PushUp(int rt)
{
    a[rt]=max(a[rt<<1],a[rt<<1|1]);
}
void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&a[rt]);
        return ;
    }
    int m=(l+r)/2;
    build(lson);
    build(rson);
    PushUp(rt);
}
void updata(int p,int sc,int l,int r,int rt)
{
    if(l==r)
    {
        a[rt]=sc;
        return ;
    }
    int m=(l+r)/2;
    if(p<=m)
        updata(p,sc,lson);
    else
        updata(p,sc,rson);
    PushUp(rt);
}
int query(int x,int y,int l,int r,int rt)
{
    if(x<=l&&r<=y)
        return a[rt];
    int m=(l+r)/2;
    int ret=-(1<<30);
    if(x<=m)
        ret=max(ret,query(x,y,lson));
    if(y>m)
        ret=max(ret,query(x,y,rson));
    return ret;
}
int main()
{
    int n,m;
    while(~scanf("%d",&n))
    {
        build(1,n,1);
        cin>>m;
        while(m--)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            cout<<query(x,y,1,n,1)<<endl;
        }
    }
}


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