51Nod 1174 区间中最大的数

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

题解

RMQ(查询区间最值)模版。代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <utility>
#define ll long long

using namespace std ;

const int MAXN = 1e4+10 ;
int max_[MAXN][32] ;
int arr_[MAXN] ;
int n ;

void rmq(){
    for ( int i = 1 ; i <= n ; i ++ ){
        max_[i][0] = arr_[i] ;
    }
    int k = log(n * 1.0) / log(2.0) ;
    for ( int j = 1 ; j <= k ; j ++ ){
        for ( int i = 1 ; i <= n ; i ++ ){
            if ( i + (1 << j) - 1 > n ) break ;
            max_[i][j] = max(max_[i][j - 1] , max_[i + (1 << (j - 1))][j - 1]) ;
        }
    }
    return ;
}

int query( int x , int y ){
    int k = log(y - x + 1.0) / log(2.0) ;
    return max(max_[x][k] , max_[y + 1 - (1 << k)][k]) ;
}

int main(){
    cin >> n ;
    for ( int i = 1 ; i <= n ; i ++ ){
        cin >> arr_[i] ;
    }
    int t ;
    cin >> t ;
    rmq() ;
    while ( t -- ){
        int x , y ;
        cin >> x >> y ;
        cout << query( x + 1 , y + 1 ) << endl ;
    }
    return 0 ;
}

猜你喜欢

转载自www.cnblogs.com/Cantredo/p/9813843.html