RMQ算法及例题(c++)

RMQ(Range Minimum/Maximum Query),用于求区间最大值和最小值。
时间复杂度:预处理:O(nlon),查询:O(1);
核心思想:dp
参考博客:
aitangyong:理解RMQ问题和ST算法的原理
Liang YJ’s Blog:哈理工训练赛2019304补题和题解
参考视频: 【算法讲堂】【电子科技大学】【ACM】树状数组与ST表
这种算法主要用到的是一个二维数组 maxx [ i ] [ j ],这个二维数组表示第 i 个数起,连续 2 ^j^ 个数,中的最大值,而maxx [ i ] [ j ] 是从 maxx[i][j-1] , maxx [ i + 2 ^j-1^ , j-1]中的最大值得来的(有点二分的思想)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int maxx[maxn][20];
int minn[maxn][20];
void rmq(int n)
{
for(int j=1;j<=20;j++)
{
for(int i=1;i<=n;i++)
{
if(i+(1<<j)-1<=n)
{
maxx[i][j]=max(maxx[i][j-1],maxx[i+(1<<(j-1))][j-1]);
minn[i][j]=min(minn[i][j-1],minn[i+(1<<(j-1))][j-1]);
}
}
}
}

查找区间最大(最小)例如 l 到 r:
则需要从二维数组中取出完全包含这段区间的子区间。

1
2
3
int k=log2(r-l+1);
int maxans=max(maxx[l][k],maxx[r-(1<<k)+1][k]);
int minans=min(minn[l][k],minn[r-(1<<k)+1][k]);

例题:
E - Balanced Lineup

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
1
2
3
4
5
6
7
8
9
10
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
1
2
3
6
3
0

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<cmath>
using namespace std;
const int maxn=50010;
int maxx[maxn][20];
int minn[maxn][20];
void rmq(int n)
{
for(int j=1;j<=20;j++)
{
for(int i=1;i<=n;i++)
{
if(i+(1<<j)-1<=n)
{
maxx[i][j]=max(maxx[i][j-1],maxx[i+(1<<(j-1))][j-1]);
minn[i][j]=min(minn[i][j-1],minn[i+(1<<(j-1))][j-1]);
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,q;
cin>>n>>q;
for(int i=1;i<=n;i++)
{
cin>>maxx[i][0];
minn[i][0]=maxx[i][0];
}
rmq(n);
int l,r;
while(q--)
{
cin>>l>>r;
int k=log2(r-l+1);
int maxans=max(maxx[l][k],maxx[r-(1<<k)+1][k]);
int minans=min(minn[l][k],minn[r-(1<<k)+1][k]);
cout<<maxans-minans<<"\n";
}
return 0;
}

坚持原创技术分享,您的支持也将成为我的动力!
-------------本文结束感谢您的阅读-------------
undefined