D - Balanced Lineup
Time Limit: 5000 MS Memory Limit: 0 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
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(Range Minimum/Maximum Query)
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 50005;
int FMAX[N][20], FMIN[N][20];
void RMQ(int n)
{
for(int j = 1; j != 20; ++j){
for(int i = 1; i <= n; ++i){
if(i + (1 << j) - 1 <= n){
FMAX[i][j] = max(FMAX[i][j - 1], FMAX[i + (1 << (j - 1))][j - 1]);
FMIN[i][j] = min(FMIN[i][j - 1], FMIN[i + (1 << (j - 1))][j - 1]);
}
}
}
}
int main()
{
int num, query;
int a, b;
while(scanf("%d %d", &num, &query) != EOF){
for(int i = 1; i <= num; ++i){
scanf("%d", &FMAX[i][0]);
FMIN[i][0] = FMAX[i][0];
}
RMQ(num);
while(query--){
scanf("%d%d", &a, &b);
int k = (int)(log(b - a + 1.0) / log(2.0));
int maxsum = max(FMAX[a][k], FMAX[b - (1 << k) + 1][k]);
int minsum = min(FMIN[a][k], FMIN[b - (1 << k) + 1][k]);
printf("%d\n", maxsum - minsum);
}
}
return 0;
}