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<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
#include<queue>
#include<math.h>
#include<map>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N=50005;
struct mmp
{
int mini,maxx;
}tree[N*4];
int n;
void build(int a,int b,int r)
{
if(a==b)
{
scanf("%d",&tree[r].maxx);
tree[r].mini=tree[r].maxx;
return;
}
int mid=(a+b)/2;
build(a,mid,r<<1);
build(mid+1,b,r<<1|1);
tree[r].mini=min(tree[r<<1].mini,tree[r<<1|1].mini);
tree[r].maxx=max(tree[r<<1].maxx,tree[r<<1|1].maxx);
}
int qurey(int a,int b,int r,int qa,int qb)//最小值
{
if(a>=qa&&b<=qb)
return tree[r].mini;
int ans=inf,mid=(a+b)/2;
if(mid>=qa)
ans=min(ans,qurey(a,mid,r<<1,qa,qb));
if(qb>mid)
ans=min(ans,qurey(mid+1,b,r<<1|1,qa,qb));
return ans;
}
int qureyy(int a,int b,int r,int qa,int qb)//最大值
{
if(a>=qa&&b<=qb)
return tree[r].maxx;
int ans=0,mid=(a+b)/2;
if(mid>=qa)
ans=max(ans,qureyy(a,mid,r<<1,qa,qb));
if(qb>mid)
ans=max(ans,qureyy(mid+1,b,r<<1|1,qa,qb));
return ans;
}
int main()
{
int q,i,a,b,c;
scanf("%d %d",&n,&q);
build(1,n,1);
for(i=0;i<q;i++)
{
scanf("%d %d",&a,&b);
printf("%d\n",qureyy(1,n,1,a,b)-qurey(1,n,1,a,b));
}
return 0;
}