51nod 1174 区间中最大的数

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
 收藏
 关注
给出一个有N个数的序列,编号0 - N - 1。进行Q次查询,查询编号i至j的所有数中,最大的数是多少。
例如: 1 7 6 3 1。i = 1, j = 3,对应的数为7 6 3,最大的数为7。(该问题也被称为RMQ问题)
Input
第1行:1个数N,表示序列的长度。(2 <= N <= 10000)
第2 - N + 1行:每行1个数,对应序列中的元素。(0 <= S[i] <= 10^9)
第N + 2行:1个数Q,表示查询的数量。(2 <= Q <= 10000)
第N + 3 - N + Q + 2行:每行2个数,对应查询的起始编号i和结束编号j。(0 <= i <= j <= N - 1)
Output
共Q行,对应每一个查询区间的最大值。
Input示例
5
1
7
6
3
1
3
0 1
1 3
3 4
Output示例
7
7
3



拿线段树的模板改一下就行

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define MAXN 200010
#define lson l,mid,p<<1
#define rson mid+1,r,p<<1|1
int sum[MAXN<<2];

void pushUp(int p)
{
    sum[p]=max(sum[p<<1],sum[p<<1|1]);
}
void build(int l,int r,int p)
{
    if(l==r){
        scanf("%d",&sum[p]);
        return ;
    }
    int mid=(l+r)>>1;
    build(lson);
    build(rson);
    pushUp(p);
}
int query(int l,int r,int p,int a,int b)
{
    if(l>=a&&b>=r)
        return sum[p];

    int ans=0;
    int mid=(l+r)>>1;
    if(mid>=a)
        ans=max(ans,query(lson,a,b));
    if(mid<b)
        ans=max(ans,query(rson,a,b));
    return ans;
}
void update(int l,int r,int p,int a,int b)
{
    if(l==r){
        sum[p]=b;
        return ;
    }
    int mid=(l+r)>>1;
    if(a<=mid) update(lson,a,b);
    else update(rson,a,b);
    pushUp(p);
}

int main()
{
    int n,m;
    char ch[5];
    //freopen("in.txt","r",stdin);
    while(~scanf("%d",&n))
    {
        int a,b;
        build(1,n,1);
        scanf("%d",&m);
        while(m--)
        {
            scanf("%d%d",&a,&b);
            //if(ch[0]=='Q')
                printf("%d
",query(1,n,1,a+1,b+1));

        }
    }
    return 0;
}


原文地址:https://www.cnblogs.com/bryce1010/p/9387103.html