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
解题思路:
用ST算法求出各区间的最大最小值即可。
注意:运算符的优先级,+ -运算优先于移位运算。
AC代码:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn = 50005;
int dp1[maxn][20], dp2[maxn][20];
void ST(int num)
{
for(int j = 1; j <= log2(num) + 1; j++)
for(int i = 1; i <= num; i++)
{
if(i + (1 << j) - 1 <= num)
{
dp1[i][j] = min(dp1[i][j - 1], dp1[i + (1 << j >> 1)][j - 1]);
dp2[i][j] = max(dp2[i][j - 1], dp2[i + (1 << j >> 1)][j - 1]);
}
}
}
int RMQ(int a, int b)
{
int k, ans;
k = (int)log2(b - a + 1.0);
ans = max(dp2[a][k], dp2[b - (1 << k) + 1][k]) - min(dp1[a][k], dp1[b - (1 << k) + 1][k]);
return ans;
}
int main()
{
int n, q, h, a, b;
scanf("%d%d", &n, &q);
for(int i = 1;i <= n; i++)
{
scanf("%d", &h);
dp1[i][0] = dp2[i][0] = h;
}
ST(n);
while(q--)
{
scanf("%d%d", &a, &b);
printf("%d\n", RMQ(a, b));
}
return 0;
}