您的位置:首页 > 其它

poj--3264 Balanced Lineup(裸的RMQ)

2016-10-22 21:41 381 查看
Description

Forthedailymilking,FarmerJohn'sNcows(1≤N≤50,000)alwayslineupinthesameorder.OnedayFarmerJohndecidestoorganizeagameofUltimateFrisbeewithsomeofthecows.Tokeepthingssimple,hewilltakeacontiguousrangeofcowsfromthemilkinglineuptoplaythegame.However,forallthecowstohavefuntheyshouldnotdiffertoomuchinheight.

FarmerJohnhasmadealistofQ(1≤Q≤200,000)potentialgroupsofcowsandtheirheights(1≤height≤1,000,000).Foreachgroup,hewantsyourhelptodeterminethedifferenceinheightbetweentheshortestandthetallestcowinthegroup.

Input

Line1:Twospace-separatedintegers,NandQ.
Lines2..N+1:Linei+1containsasingleintegerthatistheheightofcowi
LinesN+2..N+Q+1:TwointegersAandB(1≤A≤B≤N),representingtherangeofcowsfromAtoBinclusive.

Output

Lines1..Q:Eachlinecontainsasingleintegerthatisaresponsetoareplyandindicatesthedifferenceinheightbetweenthetallestandshortestcowintherange.

SampleInput

63
1
7
3
4
2
5
15
46
22


SampleOutput

6
3
0
题意:给你一个数列,不停地询问你区间【L,R】的最大值和最小值之差。
思路:由于数据特别大,所以暴力的话一定会超时的。所以考虑到用RMQ,经过简单的学习就能把这个题目给A了。
RMQ博客:http://blog.csdn.net/liang5630/article/details/7917702

AC代码:


1#include<iostream>
2#include<cstdio>
3usingnamespacestd;
4inta[200005],b[200005][40],c[200005][40];
5intmain()
6{
7intn,m,l,r;
8while(~scanf("%d%d",&n,&m))
9{
10for(inti=1;i<=n;i++)
11{
12scanf("%d",&a[i]);
13b[i][0]=c[i][0]=a[i];
14}
15for(intj=1;(1<<j)<=n;j++)
16for(inti=1;i+(1<<(j-1))<=n;i++)
17{
18b[i][j]=max(b[i][j-1],b[i+(1<<(j-1))][j-1]);
19c[i][j]=min(c[i][j-1],c[i+(1<<(j-1))][j-1]);
20//printf("%d%d%d%d\n",i,j,b[i][j],c[i][j]);
21}
22for(inti=0;i<m;i++)
23{
24scanf("%d%d",&l,&r);
25intk=0;
26while((1<<k)<=r-l+1)
27k++;
28printf("%d\n",max(b[l][k-1],b[r-(1<<(k-1))+1][k-1])-min(c[l][k-1],c[r-(1<<(k-1))+1][k-1]));
29}
30}
31return0;
32}


ViewCode


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: