poj 3264 Balanced Lineup RMQ问题

Posted mmmqqdd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 3264 Balanced Lineup RMQ问题相关的知识,希望对你有一定的参考价值。

Balanced Lineup

Time Limit: 1 Sec  Memory Limit: 256 MB

题目连接

http://poj.org/problem?id=3264

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

 

HINT

 

题意

给你n个数,然后查询区间的最大值减去最小值是多少

 

题解:

RMQ,我用ST来做,也可线段树。

注意: j+1<<(i-1) 和 j+(1<<(i-1)) 是不一样的,位运算优先级还不如加法。

 

代码:

技术图片
 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cmath>
 5 using namespace std;
 6 #define N 200050
 7 int n,m,mi[N][21],mx[N][21];
 8 template<typename T>void read(T &x)
 9 {
10   int k=0; char c=getchar();
11   x=0;
12   while(!isdigit(c)&&c!=EOF)c^=c==-,c=getchar();
13   if(c==EOF)exit(0);
14   while(isdigit(c))x=x*10+c-0,c=getchar();
15   x=k?-x:x;
16 }
17 int query_max(int x,int y)
18 {
19   int k=(int)(log(y-x+1)/log(2));
20   return max(mx[x][k],mx[y-(1<<k)+1][k]);
21 }
22 int query_min(int x,int y)
23 {
24   int k=(int)(log(y-x+1)/log(2));
25   return min(mi[x][k],mi[y-(1<<k)+1][k]);
26 }
27 int main()
28 {
29   #ifndef ONLINE_JUDGE
30   freopen("aa.in","r",stdin);
31   #endif
32   read(n);read(m);
33   for(int i=1;i<=n;i++)read(mx[i][0]),mi[i][0]=mx[i][0];
34   for(int i=1;i<=20;i++)
35     for(int j=1;j<=n;j++)
36       if (j+(1<<(i-1))>n)break;
37       else
38     {
39       mx[j][i]=max(mx[j][i-1],mx[j+(1<<(i-1))][i-1]);
40       mi[j][i]=min(mi[j][i-1],mi[j+(1<<(i-1))][i-1]);
41     }
42   for(int i=1;i<=m;i++)
43     {
44       int x,y;
45       read(x);read(y);
46       int ans=query_max(x,y)-query_min(x,y);
47       printf("%d\n",ans);
48     }
49 }
View Code

 

以上是关于poj 3264 Balanced Lineup RMQ问题的主要内容,如果未能解决你的问题,请参考以下文章

Balanced Lineup POJ - 3264

POJ 3264 Balanced Lineup

POJ3264 Balanced Lineup

poj3264 Balanced Lineup 2011-12-20

POJ 3264 Balanced Lineup

POJ 3264 Balanced Lineup