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<iostream>
#include<stdio.h>
using namespace std;
const int MAXN = 50000 + 10;
struct f
{
int maxx;
int minn;
int val;
}a[MAXN * 4];
void build(int left , int right , int rt)
{
if(left == right)
{
scanf("%d" ,&a[rt].val);
a[rt].maxx = a[rt].minn = a[rt].val;
return;
}
int mid = (left + right) >> 1;
build(left , mid , rt << 1);
build(mid + 1, right , rt << 1 | 1);
a[rt].maxx = max(a[rt << 1].maxx , a[rt << 1 | 1].maxx);
a[rt].minn = min(a[rt << 1].minn , a[rt << 1 | 1].minn);
//a[rt].val = a[rt].maxx - a[rt].minn;
}
int query1(int x , int y , int left , int right , int rt)
{
if(left >= x && right <= y)
{
return a[rt].maxx;
}
int mid = (left + right) >> 1;
int Max = 0 ;
if(mid >= x)
Max = max(Max , query1(x , y , left , mid , rt << 1));
if(mid < y)
Max = max(Max , query1(x , y , mid + 1 , right , rt << 1 | 1));
return Max;
}
int query2(int x , int y , int left , int right , int rt)
{
if(left >= x && right <= y)
{
return a[rt].minn;
}
int mid = (left + right) >> 1;
int Min = 1e9 ;
if(mid >= x)
Min = min(Min , query2(x , y , left , mid , rt << 1));
if(mid < y)
Min = min(Min , query2(x , y , mid + 1 , right , rt << 1 | 1));
return Min;
}
int main()
{
int n , q;
scanf("%d %d" , &n , &q);
build(1 , n , 1);
//for(int i = 1; i <= 30 ; i ++)
// cout << a[i].minn << " ";
//cout << endl;
while(q --)
{
int x , y;
scanf("%d %d" , &x , &y);
int t1 = query1(x, y , 1 , n , 1);
int t2 = query2(x, y , 1 , n , 1);
printf("%d\n" , t1 - t2);
}
return 0;
}