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,但是用线段树也可以过,只是代码量会大一些,下面是代码:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct tree{
int l,r,mx,mn;
tree *lc,*rc;
};
tree *make(){
return (tree *)(malloc(sizeof(tree)));
}
int read(){
int s=0;
char c=getchar();
while(!(c>='0'&&c<='9')){
c=getchar();
}
while(c>='0'&&c<='9'){
s*=10;
s+=c-'0';
c=getchar();
}
return s;
}
void build(tree *root,int l,int r){
root->l=l;
root->r=r;
if(l==r){
root->lc=root->rc=NULL;
root->mn=root->mx=read();
return;
}
int m=l+r>>1;
build(root->lc=make(),l,m);
build(root->rc=make(),m+1,r);
root->mn=min(root->lc->mn,root->rc->mn);
root->mx=max(root->lc->mx,root->rc->mx);
}
int askmx(tree *root,int l,int r){
if(root->l==l&&root->r==r){
return root->mx;
}
int m=root->l+root->r>>1;
if(r<=m){
return askmx(root->lc,l,r);
}
if(l>m){
return askmx(root->rc,l,r);
}
return max(askmx(root->lc,l,m),askmx(root->rc,m+1,r));
}
int askmn(tree *root,int l,int r){
if(root->l==l&&root->r==r){
return root->mn;
}
int m=root->l+root->r>>1;
if(r<=m){
return askmn(root->lc,l,r);
}
if(l>m){
return askmn(root->rc,l,r);
}
return min(askmn(root->lc,l,m),askmn(root->rc,m+1,r));
}
int main(){
int n=read(),q,l,r;
q=read();
tree *root=make();
build(root,1,n);
while(q--){
l=read();
r=read();
printf("%d\n",askmx(root,l,r)-askmn(root,l,r));
}
return 0;
}