Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 55464 | Accepted: 25993 | |
Case Time Limit: 2000MS |
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
代码
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
const int MAX=100001;
int arr[MAX];
struct segtree{
int valsmall;
int valbig;
int add;
}segtree[MAX*4+1];
void build(int root,int *arr,int start,int end){
segtree[root].add=0;
if(start==end){
segtree[root].valsmall=arr[start];
segtree[root].valbig=arr[start];
return ;
}
else
{
int mid=(start+end)/2;
build(root*2+1,arr,start,mid);
build(root*2+2,arr,mid+1,end);
segtree[root].valbig=max(segtree[root*2+1].valbig,segtree[root*2+2].valbig);
segtree[root].valsmall=min(segtree[root*2+1].valsmall,segtree[root*2+2].valsmall);
}
}
int query_small(int root,int c_start,int c_end,int q_start,int q_end){
if(c_start>q_end || c_end<q_start) return INT_MAX;
if(q_start<=c_start && c_end<=q_end){
return segtree[root].valsmall;
}
int mid=(c_start+c_end)/2;
return min(query_small(root*2+1,c_start,mid,q_start,q_end),query_small(root*2+2,mid+1,c_end,q_start,q_end));
}
int query_big(int root,int c_start,int c_end,int q_start,int q_end){
if(c_start>q_end || c_end<q_start) return INT_MIN;
if(q_start<=c_start && c_end<=q_end){
return segtree[root].valbig;
}
int mid=(c_start+c_end)/2;
return max(query_big(root*2+1,c_start,mid,q_start,q_end),query_big(root*2+2,mid+1,c_end,q_start,q_end));
}
int main(){
// freopen("E://1001.txt","r",stdin);
int N,Q;
cin>>N>>Q;
for(int i=1;i<=N;i++)
{
scanf("%d",&arr[i]);
}
build(0,arr,1,N);
for(int i=0;i<Q;i++)
{
int a,b;
scanf("%d %d",&a,&b);
int small=query_small(0,1,N,a,b);
int big=query_big(0,1,N,a,b);
cout<<big-small<<endl;
}
}