RMQ---Balanced Lineup

RMQ是在给定的一个区间内最值查询的一个算法,主要包括处理和查询两个部分,在预处理中,用的是动态规划去处理,首先A[i]是要求区间最值的数列,F[i, j]表示从第i个数起连续2^j个数中的最大值F[i,0]就等于A[i]为了高效,把F[i, j]分为两半,F[i,j]就是这两段各自最大值中的最大值所以状态转移方程F[i, j]=max(F[i,j-1], F[i + 2^(j-1),j-1])

void RMQ(int n)

{

int i, j;

for (j = 1; j < 20; j++)

{

for (i = 1; i <= n; i++)

{

if (i + (1 << j) - 1 <= n)

{

maxsum[i][j] = max(maxsum[i][j - 1], maxsum[i + (1 << (j - 1))][j - 1]);

minsum[i][j] = min(minsum[i][j - 1], minsum[i + (1 << (j - 1))][j - 1]);

}

}

}

切记j在外,i在前

在查询部分,切记你要算出来对于给定的区间进行求解用log2求解,并且是要比较在区间中,两部分的最大值

for (i = 1; i <= m; i++)

{

scanf("%d %d", &x, &y);

k = (int)log2(y - x + 1);

ma = max(maxsum[x][k], maxsum[y - (1 << k) + 1][k]);

mi = min(minsum[x][k], minsum[y - (1 << k) + 1][k]);

printf("%d", ma - mi);

}




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 ≤  A ≤  B ≤  N), 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

题目大意:一共有N头牛,每头牛的高度为height,然后询问你Q次,问你A与B内,最高的那头牛与最低的那头牛相差多少

数据范围:1 ≤ N ≤ 50,000,1 ≤ Q ≤ 200,000,1 ≤ height ≤ 1,000,000,1 ≤ A ≤ B ≤ N

涉及算法:RMQ


解题思路:这是一道标准的RMQ,题的正确思路都在上面,这道题WA了几发,主要是因为提交格式和超时,超时原因是用的C++输入输出方式,这是蛮尴尬的一点,c++的比c会耗时一些,所以考虑到这种情况,以后这种擦边线球的卡时间的情况,还是优先考虑c的输入输出


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值