Balanced Lineup
Description
For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.
Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.
Input
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i
Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.
Output
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
【思路分析】
一道裸的区间最值问题,还是用RMQ写的,和NYOJ119这一题一模一样。
代码如下:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#define maxn 50005
using namespace std;
int maxSum[maxn][20], minSum[maxn][20];
void RMQ(int num) //预处理->O(nlogn)
{
for(int j = 1;j < 20;j++)
{
for(int i = 1;i <= num;i++)
{
if((i + (1 << j) - 1) <= num)
{
maxSum[i][j] = max(maxSum[i][j - 1],maxSum[i + (1 << (j - 1))][j - 1]);
minSum[i][j] = min(minSum[i][j - 1],minSum[i + (1 << (j - 1))][j - 1]);
}
}
}
}
int main()
{
int num,query;
int src,des;
scanf("%d %d",&num,&query);
for(int i = 1;i <= num;i++)
{
scanf("%d",&maxSum[i][0]);
minSum[i][0] = maxSum[i][0];
}
RMQ(num);
while(query--)//O(1)查询
{
scanf("%d %d",&src,&des);
int k = (int)(log(des - src + 1.0) / log(2.0));//中间位置
int ansMax = max(maxSum[src][k],maxSum[des - (1 << k) + 1][k]);
int ansMin = min(minSum[src][k],minSum[des - (1 << k) + 1][k]);
printf("%d\n",ansMax - ansMin);
}
return 0;
}