设为首页 加入收藏

TOP

poj 3264 Balanced Lineup RMQ线段树实现
2015-07-20 17:21:00 来源: 作者: 【 】 浏览:3
Tags:poj 3264 Balanced Lineup RMQ 线段 实现
Balanced Lineup
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

Line 1: Two space-separated integers, N and Q.
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 ≤ ABN), representing the range of cows from A to B inclusive.

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.2cto.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 ; }
   
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 1338 Game Prediction 下一篇BZOJ 3029 守卫者的挑战 期望DP

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)
·使用华为开发者空间 (2025-12-27 04:19:24)
·Getting Started wit (2025-12-27 03:49:24)
·Ubuntu 上最好用的中 (2025-12-27 03:49:20)