RMQ(区间求最值)

1. 概述

RMQ(Range Minimum/Maximum Query),即区间最值查询,是指这样一个问题:对于长度为n的数列A。回答若干询问RMQ(A,i,j)(i,j<=n)。返回数列A中下标在i,j之间的最小/大值。

这两个问题是在实际应用中常常遇到的问题,以下介绍一下解决这两种问题的比較高效的算法。当然,该问题也能够用线段树(也叫区间树)解决,算法复杂度为:O(N)~O(logN)。这里我们暂不介绍。


2.RMQ算法

对于该问题,最easy想到的解决方式是遍历。复杂度是O(n)。

但当数据量非常大且查询非常频繁时,该算法无法在有效的时间内查询出正解。

本节介绍了一种比較高效的在线算法(ST算法)解决问题。

所谓在线算法。是指用户每输入一个查询便立即处理一个查询。该算法一般用较长的时间做预处理,待信息充足以后便能够用较少的时间回答每一个查询。ST(Sparse Table)算法是一个很有名的在线处理RMQ问题的算法,它能够在O(nlogn)时间内进行预处理,然后在O(1)时间内回答每一个查询。


(一)首先是预处理,用动态规划(DP)解决。

设A[i]是要求区间最值的数列,F[i, j]表示从第i个数起连续2^j个数中的最大值。

(DP的状态)

比如:

A数列为:3 2 4 5 6 8 1 2 9 7

F[1,0]表示第1个数起。长度为2^0=1的最大值,事实上就是3这个数。同理 F[1,1] = max(3,2) = 3, F[1,2]=max(3,2,4,5) = 5。F[1,3] = max(3,2,4,5,6,8,1,2) = 8;

而且我们能够easy的看出F[i,0]就等于A[i]。

(DP的初始值)

这样,DP的状态、初值都已经有了,剩下的就是状态转移方程。

我们把F[i,j]平均分成两段(由于f[i。j]一定是偶数个数字)。从 i 到i + 2 ^ (j - 1) - 1为一段,i + 2 ^ (j - 1)到i + 2 ^ j - 1为一段(长度都为2 ^ (j - 1))。用上例说明,当i=1,j=3时就是3,2,4,5 和 6,8,1,2这两段。

F[i,j]就是这两段各自最大值中的最大值。

于是我们得到了状态转移方程F[i, j]=max(F[i,j-1], F[i + 2^(j-1),j-1])。

代码例如以下:

void RMQ(int num) //预处理->O(nlogn)
{
	for(int j = 1; j < 20; ++j)
		for(int i = 1; i <= num; ++i)
			if(i + (1 << j) - 1 <= num)
			{
				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。这是为什么呢?能够是i在外,j在内吗?


答案是不能够。由于我们须要理解这个状态转移方程的意义。

状态转移方程的含义是:先更新全部长度为F[i,0]即1个元素。然后通过2个1个元素的最值,获得全部长度为F[i,1]即2个元素的最值,然后再通过2个2个元素的最值,获得全部长度为F[i,2]即4个元素的最值,以此类推更新全部长度的最值。

而假设是i在外。j在内的话,我们更新的顺序就是F[1,0],F[1,1],F[1,2],F[1,3],表示更新从1開始1个元素,2个元素。4个元素。8个元素(A[0],A[1],....A[7])的最值。这里F[1,3] = max(max(A[0],A[1],A[2],A[3]),max(A[4],A[5],A[6],A[7]))的值。可是我们根本没有计算max(A[0],A[1],A[2],A[3])和max(A[4],A[5],A[6],A[7])。所以这个方案肯定是错误的。(这种话非常多没有计算会出现最小值为0这个初始化的值)


为了避免这种错误,一定要好好理解这个状态转移方程所代表的含义。



(二)然后是查询。

假如我们须要查询的区间为(i,j)。那么我们须要找到覆盖这个闭区间(左边界取i。右边界取j)的最小幂(能够反复,比方查询5。6,7,8,9,我们能够查询5678和6789)。

由于这个区间的长度为j - i + 1,所以我们能够取k=log2( j - i + 1),则有:RMQ(A, i, j)=max{F[i , k], F[ j - 2 ^ k + 1, k]}。

举例说明。要求区间[2,8]的最大值,k = log2(8 - 2 + 1)= 2,即求max(F[2, 2],F[8 - 2 ^ 2 + 1, 2]) = max(F[2, 2],F[5, 2])。


在这里我们也须要注意一个地方,就是<<运算符和+-运算符的优先级。

比方这个表达式:5 - 1 << 2是多少?


答案是:4 * 2 * 2 = 16。所以我们要写成5 - (1 << 2)才是5-1 * 2 * 2 = 1。


以下给出详细的模板题:

poj:3264

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 35537   Accepted: 16711
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 ≤ 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

Source

题意:给出区间,求区间内最大值和最小值的差

模板RMQ,但也能够用线段数做

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 50010;//别开太大,否则会MLE
const int INF = 0x3f3f3f3f;
int n,q;
int a[maxn];
int maxnum[maxn][22];
int minnum[maxn][22];
void RMQ()
{
    for(int i =1 ; i <= 20; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            if(j + (1<<i) -1 <=n)
            {
                maxnum[j][i] = max(maxnum[j][i-1], maxnum[j+(1<<(i-1))][i-1]);
                minnum[j][i] = min(minnum[j][i-1], minnum[j+(1<<(i-1))][i-1]);
            }
        }
    }
}
int main()
{
#ifdef xxz
    freopen("in","r",stdin);
#endif // xxz
    scanf("%d%d",&n,&q);
    memset(maxnum,0,sizeof(maxnum));
    memset(minnum,0,sizeof(minnum));
    for(int i = 1; i <= n; i++)
    {
        scanf("%d",&a[i]);
        maxnum[i][0] =  minnum[i][0] = a[i];
    }
    RMQ();
    int a,b;
    while(q--)
    {
        scanf("%d%d",&a,&b);
        int k = log(b-a+1.0)/log(2.0);
        int maxx = max(maxnum[a][k],maxnum[b-(1<<k)+1][k]);
        int minn = min(minnum[a][k],minnum[b-(1<<k)+1][k]);
        printf("%d
",maxx - minn);

    }
    return 0;
}




原文地址:https://www.cnblogs.com/gccbuaa/p/6784844.html