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
Source
这道题本来不打算写下来,但想练手没就写了一遍,没想到错了许多次,是由于
if(x>=Mid+1),当时没写+1;
#include<stdio.h>
#include<iostream>
using namespace std;
int a[1000005];
struct ele
{
int left;
int right;
int Max;
int Min;
}p[10000029];
void build(int L,int R,int step)
{
p[step].left=L;
p[step].right=R;
if(L==R)
p[step].Max=p[step].Min=a[L];
else
{
int Mid=(L+R)/2;
build(L,Mid,2*step);
build(Mid+1,R,2*step+1);
p[step].Max=max(p[2*step].Max,p[2*step+1].Max);
p[step].Min=min(p[2*step].Min,p[2*step+1].Min);
}
}
int Max(int x,int y,int step)
{
if(p[step].left==x&&p[step].right==y)
return p[step].Max;
else
{
int Mid=(p[step].left+p[step].right)/2;
if(y<=Mid)
return Max(x,y,2*step);
else
if(x>=Mid+1)
return Max(x,y,2*step+1);
else
return max(Max(x,Mid,2*step),Max(Mid+1,y,2*step+1));
}
}
int Min(int x,int y,int step)
{
if(p[step].left==x&&p[step].right==y)
return p[step].Min;
else
{
int Mid=(p[step].left+p[step].right)/2;
if(y<=Mid)
return Min(x,y,2*step);
else
if(x>=Mid+1)
return Min(x,y,2*step+1);
else
return min(Min(x,Mid,2*step),Min(Mid+1,y,2*step+1));
}
}
int main()
{
int N,Q;
int i;
int x,y;
while(scanf("%d%d",&N,&Q)!=EOF)
{
for(i=1;i<=N;i++)
scanf("%d",&a[i]);
build(1,N,1);
while(Q--)
{
scanf("%d%d",&x,&y);
printf("%d\n",Max(x,y,1)-Min(x,y,1));
}
}
return 0;
}