The Water Problem HDU - 5443【RMQ模版题】

  题目就是给你a1~an的一串数,让你求l到r的一段范围内的最大值,一道RMQ的模版题。

In Land waterless, water is a very limited resource. People always fight for the biggest source of water. Given a sequence of water sources with a1,a2,a3,...,ana1,a2,a3,...,an representing the size of the water source. Given a set of queries each containing 22 integers ll and rr, please find out the biggest water source between alal and arar.

Input

First you are given an integer T(T≤10)T(T≤10) indicating the number of test cases. For each test case, there is a number n(0≤n≤1000)n(0≤n≤1000) on a line representing the number of water sources. nn integers follow, respectively a1,a2,a3,...,ana1,a2,a3,...,an, and each integer is in {1,...,106}{1,...,106}. On the next line, there is a number q(0≤q≤1000)q(0≤q≤1000) representing the number of queries. After that, there will be qq lines with two integers lland r(1≤l≤r≤n)r(1≤l≤r≤n) indicating the range of which you should find out the biggest water source.

Output

For each query, output an integer representing the size of the biggest water source.

Sample Input

3
1
100
1
1 1
5
1 2 3 4 5
5
1 2
1 3
2 4
3 4
3 5
3
1 999999 1
4
1 1
1 2
2 3
3 3

Sample Output

100
2
3
4
4
5
1
999999
999999
1

完整代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <queue>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
int N,M;
int a[1005];
int dp[1005][20];
void RMQ()
{
    for(int i=1; i<=N; i++) dp[i][0]=a[i];
    for(int j=1; (1<<j)<=N; j++)
    {
        for(int i=1; i+(1<<j)-1<=N; i++)
        {
            dp[i][j]=max(dp[i][j-1], dp[i+(1<<(j-1))][j-1]);
        }
    }
}
int Query_max(int l, int r)
{
    int i=0;
    while(l-1+(1<<i)<=r) i++;
    i--;
    return max(dp[l][i], dp[r-(1<<i)+1][i]);
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        memset(dp, 0, sizeof(dp));
        memset(a, 0, sizeof(a));
        scanf("%d",&N);
        for(int i=1; i<=N; i++)scanf("%d",&a[i]);
        RMQ();
        scanf("%d",&M);
        while(M--)
        {
            int e1,e2;
            scanf("%d%d",&e1,&e2);
            printf("%d\n",Query_max(e1, e2));
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41730082/article/details/81260207
今日推荐