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

 

转载于:https://www.cnblogs.com/mmmqqdd/p/10759432.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值