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
Line 1: Two space-separated integers, N and Q.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
這題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) {www.Bkjia.com 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 ,tall-shor) ; } return 0 ; }