Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 12699 | Accepted: 5868 | |
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
Source
编译一次过,AC也一次过。。。RP啊。。。
#include<cstdio>
#define LL(x) (x<<1)
#define RR(x) (x<<1|1)
#define MAX 50010
int w[MAX];
int max(int a,int b)
{
if(a>b) return a;
return b;
}
int min(int a,int b)
{
if(a>b) return b;
return a;
}
int Nmax,Nmin;
struct Seg_Tree
{
int left,right,max,min;
int mid() { return (left+right)>>1; }
}tree[MAX*3];
void build(int left,int right,int idx)
{
tree[idx].left=left;
tree[idx].right=right;
if(left==right)
{
tree[idx].max=w[left];
tree[idx].min=w[left];
return;
}
int mid=tree[idx].mid();
build(left,mid,LL(idx));
build(mid+1,right,RR(idx));
tree[idx].max=max(tree[LL(idx)].max,tree[RR(idx)].max);
tree[idx].min=min(tree[LL(idx)].min,tree[RR(idx)].min);
}
void query(int left,int right,int idx)
{
if(left<=tree[idx].left&&right>=tree[idx].right)
{
Nmax=max(Nmax,tree[idx].max);
Nmin=min(Nmin,tree[idx].min);
return ;
}
int mid=tree[idx].mid();
if(left<=mid) query(left,right,LL(idx));
if(right>mid) query(left,right,RR(idx));
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++) scanf("%d",&w[i]);
build(1,n,1);
for(int i=1;i<=m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
Nmax=-100000000;
Nmin=1<<31-1;
query(a,b,1);
printf("%d/n",Nmax-Nmin);
}
}
return 0;
}