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
题意:
给你一个区间和多次询问求这个区间最大减最小值的值
思路:线段树建两个一个用来找最大一个找最小ac
代码:
#include<iostream>
#include<cstdio>
#define INF 0x3f3f3f3f;
using namespace std;
struct node{
int x,y;
}pp[1000009];
void pushup(int step)
{
pp[step].x = min(pp[step<<1].x,pp[step<<1|1].x);
pp[step].y = max(pp[step<<1].y,pp[step<<1|1].y);
}
void build(int l,int r,int step)
{
if(l == r)
{
scanf("%d",&pp[step].x);
pp[step].y = pp[step].x;
return ;
}
int m = (l+r)>>1;
build(l,m,step<<1);
build(m+1,r,step<<1|1);
pushup(step);
}
int query(int L,int R,int l,int r,int step)
{
if(L<=l&&r<=R)
{
return pp[step].x;
}
int m = (r+l)>>1;
int ret=INF;
if(L<=m)
{
ret=min(ret,query(L,R,l,m,step*2));
}
if(R>m)
{
ret=min(ret,query(L,R,m+1,r,step*2+1));
}
return ret;
}
int query1(int L,int R,int l,int r,int step)
{
if(L<=l&&r<=R)
{
return pp[step].y;
}
int m = (r+l)>>1;
int ret= 0;
if(L<=m)
{
ret=max(ret,query1(L,R,l,m,step*2));
}
if(R>m)
{
ret=max(ret,query1(L,R,m+1,r,step*2+1));
}
return ret;
}
int main()
{
int n,q;
scanf("%d%d",&n,&q);
build(1,n,1);
int a,b;
for(int i=0;i<q;++i)
{
scanf("%d%d",&a,&b);
int g = query1(a,b,1,n,1);//询问最大
int y = query(a,b,1,n,1);//询问最小
printf("%d\n",g-y);
}
return 0;
}