POJ-3264
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
Line 1: Two space-separated integers, N and Q.
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
Lines 1…Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
#include
#include
#define INF 0x3f3f3f3f
using namespace std;
const int N = 50005;
int heigh[N];
int maxn[4 * N];
int minn[4 * N];
int lazy[4 * N];
void push_up(int root){
maxn[root] = max(maxn[root << 1], maxn[root << 1 | 1]);
minn[root] = min(minn[root << 1], minn[root << 1 | 1]);
}
void build(int root, int l, int r){
if(l == r){
scanf("%d", &heigh[l]);
maxn[root] = heigh[l];
minn[root] = maxn[root];
return;
}
int mid = l + r >> 1;
build(root << 1, l, mid);
build(root << 1 | 1, mid + 1, r);
push_up(root);
}
int query_max(int L, int R, int root, int l, int r){
if(L <= l && R >= r){
return maxn[root];
}
int mid = l + r >> 1;
int ans = 0;
if(L <= mid)
ans = max(ans, query_max(L, R, root << 1, l, mid));
if(R > mid)
ans = max(ans, query_max(L, R, root << 1 | 1, mid + 1, r));
return ans;
}
int query_min(int L, int R, int root, int l, int r){
if(L <= l && R >= r){
return minn[root];
}
int mid = l + r >> 1;
int ans = INF;
if(L <= mid)
ans = min(ans, query_min(L, R, root << 1, l, mid));
if(R > mid)
ans = min(ans, query_min(L, R, root << 1 | 1, mid + 1, r));
return ans;
}
int main(){
int n, q;
// freopen("data1.in","r",stdin);
scanf("%d %d", &n, &q);
build(1, 1, n);
while(q--){
int a, b;
scanf("%d %d", &a, &b);
int max1 = query_max(a, b, 1, 1, n);
int min1 = query_min(a, b, 1, 1, n);
printf("%d\n", max1 - min1);
}
return 0;
}