Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 36613 | Accepted: 17141 | |
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
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
这题RMQ问题,RMQ最好使用使用ST算法实现,效率可能比较高。。我用的线段树,用了1500ms。。。(掩面
可能是我写的渣吧,等有时间学一下st算法,毕竟用线段树能不能AC可能要看人品了。或许是我的代码写的太渣,还有可以优化的地方却没有优化。就这样吧。代码还是比较容易理解的
#include
#include
#define MAX 501000
struct tree{
int t,s;
}st[MAX*4];
int tall=INT_MIN,shor=INT_MAX ;
int max(int a ,int b)
{
return a>b?a:b;
}
int min(int a ,int b)
{
return a>b?b:a ;
}
void build(int left , int right , int pos)
{
if(left == right)
{
scanf("%d",&st[pos].t);
st[pos].s = st[pos].t;
return ;
}
int mid = (left + right)>>1;
build(left,mid,pos<<1);
build(mid+1,right,pos<<1|1) ;
st[pos].t = max(st[pos<<1].t,st[pos<<1|1].t) ;
st[pos].s = min(st[pos<<1].s,st[pos<<1|1].s) ;
}
//L,R大区间,
void query(int L,int R,int x, int y ,int pos)
{
if(L == x && R == y)
{
tall = max(tall,st[pos].t);
shor = min(shor,st[pos].s);
return ;
}
int mid = (L+R)>>1;
if(mid < x)
{
query(mid+1,R,x,y,pos<<1|1);
}
else if(mid >= y)
{
query(L,mid,x,y,pos<<1) ;
}
else
{
query(L,mid,x,mid,pos<<1);
query(mid+1,R,mid+1,y,pos<<1|1) ;
}
}
int main()
{
int n,q;
scanf("%d%d",&n,&q);
build(1,n,1);
for(int i = 0 ; i < q ; ++i)
{
int a,b;
scanf("%d%d",&a,&b);
tall=INT_MIN,shor=INT_MAX ;
query(1,n,a,b,1) ;
printf("%d\n",tall-shor) ;
}
return 0 ;
}