RMQ算法詳解


RMQ算法,是一個快速求區間最值的離線算法,預處理時間復雜度O(n*log(n)),查詢O(1),所以是一個很快速的算法。

當然這個問題用線段樹同樣能夠解決,算法復雜度為:O(N)~O(logN) 。

RMQ:

RMQ(Range Minimum/Maximum Query),即區間最值查詢,是指這樣一個問題:對於長度為n的數列A,

回答若干詢問RMQ(A,i,j)(i,j<=n),返回數列A中下標在i,j之間的最小/大值。

分析:

對於該問題,最容易想到的解決方案是遍歷,復雜度是O(n)。但當數據量非常大且查詢很頻繁時,該算法無法在有效的時間內查詢出正解。

本節介紹了一種比較高效的在線算法(ST算法)解決這個問題。所謂在線算法,是指用戶每輸入一個查詢便馬上處理一個查詢。該算法一般用較長的時間做預處理,待信息充足以后便可以用較少的時間回答每個查詢。ST(Sparse Table)算法是一個非常有名的在線處理RMQ問題的算法

 

預處理:

設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;

並且我們可以容易的看出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)    // 這里j的范圍根據具體題目數據定義
        for(int i = 1; i <= num; ++i)    // num為數組內整數的個數
            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是內循環? 能不能調換一下嘞?

答案是不可以。因為我們需要理解這個狀態轉移方程的意義。
狀態轉移方程的含義是:先更新所有長度為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]),所以這樣的方法肯定是錯誤的。
為了避免這樣的錯誤,一定要好好理解這個狀態轉移方程所代表的含義。
先自己考慮一下哈!

 

查詢:

假如我們需要查詢的區間為(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]);

在這里我們也需要注意一個地方,就是<<運算符和+-運算符的優先級。

 

實戰一下:

 

 

Time Limit: 5000MS   Memory Limit: 65536K
     
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

 

 

題目大意:

     輸入一組整數,然后給定一下查詢區間,輸出查詢區間內最大值與最小值的差值。

代碼:

 1 #include <stdio.h>
 2 #include <math.h>
 3 #include <string.h>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int maxnum[50010][20];
 8 int minnum[50010][20];
 9 int main()
10 {
11     int num,n,q,i,j,x,y;
12     while (~scanf("%d%d",&n,&q))
13     {
14         for (i = 1; i <= n; i ++)
15         {
16             scanf("%d",&num);
17             maxnum[i][0] = minnum[i][0] = num;   // 先預處理2^0長度的 
18         }
19         
20         for (j = 1; (1<<j) <= n; j ++)
21          for (i = 1; i+(1<<j)-1 <= n; i ++)   // 預處理 
22          {                                                 
23             maxnum[i][j] = max(maxnum[i][j-1],maxnum[i + (1<<(j-1))][j-1]);
24             minnum[i][j] = min(minnum[i][j-1],minnum[i + (1<<(j-1))][j-1]);
25          }
26             
27         while (q --)
28         {
29             scanf("%d%d",&x,&y);
30             int z = 0;
31             while ((1<<(z+1)) <= y-x+1) z ++;
32             int ans = max(maxnum[x][z],maxnum[y-(1<<z)+1][z])
33                      - min(minnum[x][z],minnum[y-(1<<z)+1][z]);
34             printf("%d\n",ans);
35         }
36     }
37     return 0;
38 }

 

 

 

 

 

本文參考:http://blog.csdn.net/liang5630/article/details/7917702


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM