Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 32820 | Accepted: 15447 | |
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
#include <iostream>
#include <stdio.h>
using namespace std; #define MAXN 50000
#define INF 99999999
int MaxV,MinV; struct Node{
int L,R;
int ma,mi; //区间[L,R]的最大值和最小值
}a[MAXN*]; int Max(int x,int y)
{
return x>y?x:y;
} int Min(int x,int y)
{
return x<y?x:y;
} void Build(int d,int l,int r) //建立线段树
{
if(l==r){ //找到叶子节点
scanf("%d",&a[d].ma);
a[d].mi = a[d].ma;
a[d].L = l;
a[d].R = r;
return ;
} //初始化当前节点的信息
a[d].L = l;
a[d].R = r; //建立线段树
int mid = (l+r)>>;
Build(d<<,l,mid);
Build(d<<|,mid+,r); //更新当前节点的信息
a[d].ma = Max(a[d<<].ma,a[d<<|].ma);
a[d].mi = Min(a[d<<].mi,a[d<<|].mi);
} void Query(int d,int l,int r) //查询区间[l,r]的最大值和最小值的差
{
if(a[d].ma<MaxV && a[d].mi>MinV) //优化,如果当前区间的最大值和最小值在MaxV和MinV之间,则没必要继续递归该区间。能快100MS
return ;
if(a[d].L==l && a[d].R==r){ //找到终止节点
MaxV = Max(MaxV,a[d].ma);
MinV = Min(MinV,a[d].mi);
return ;
} int mid = (a[d].L+a[d].R)/;
if(mid>=r){ //左孩子找
Query(d<<,l,r);
}
else if(mid<l){ //右孩子找
Query(d<<|,l,r);
}
else{ //左孩子、右孩子都找
Query(d<<,l,mid);
Query(d<<|,mid+,r);
}
} int main()
{
int n,q,A,B;
scanf("%d%d",&n,&q);
Build(,,n);
while(q--){ //q次询问
scanf("%d%d",&A,&B);
MaxV = -INF;
MinV = INF;
Query(,A,B);
printf("%d\n",MaxV-MinV);
}
return ;
}
Freecode : www.cnblogs.com/yym2013