RMQ(Range Minimum/Maximum Query)题目是求区间最值的题目。
这里主要简单介绍一下ST算法
我们知道如果使用朴素的算法求解区间最大值的话,假设数列长度为n,那么每询问一次的时间复杂度是O(n),在数列较长的情况下,这种方法是十分慢的,我们采用类似树状数组的思想,维护一个DP数组,有DP[i][j]值为以i为下标的后个数的这段区间内的最值。
举个简单的例子,假设有数列arr[5] = {5, 5, 5, 2, 1},那么DP[i][0]值就为a[i],因为,所以我们可以对其进行直接的赋值操作,而对于DP[i][1]我们知道他是arr[i],arr[i + 1]两个数字中的最值。所以他的结果就是DP[i][0]和DP[i][1]中的最值,同理可知DP[i][2]就为DP[i][1]和DP[i + 2][1],此时我们归纳推出DP[i][j]的值为DP[i][j - 1]和DP[i + (1 << j)][j - 1]的最值,这样我们就维护出了DP数组。那么接下来的问题就是如何求解某个区间中的最大值,其实非常简单,我们只要把区间的长度n分成log2(n)的两段即可,也就是区间[l, r]的最值,我们有,在计算时,我们的结果就是DP[l][k]和DP[r - (1 << k ) + 1][k]的最值。这就是ST算法的全部内容,也就解决区间最值的在线算法。当然解决这类问题也可以使用线段树。
使用ST算法的时候需要注意几点,首先需要注意DP数组的下标范围,DP[i][j]的i显然是这个序列的长度n,而j则是即可。其次在创建DP数组的时候需要注意i + 1 << j大于序列长度的情况,这样的我们直接break跳出当前循环即可
举一个简单的题目来说明这个算法的用法。
Balanced Lineup
Time Limit: 5000MS |
|
Memory Limit: 65536K |
Total Submissions: 45880 |
|
Accepted: 21556 |
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
题意是给出一个序列,然后有若干个询问,求每个询问给出的区间内最大值最小值的差值。
方法就是利用ST算法维护区间的最大值和最小值两个DP数组,然后设计两个求最值的函数即可。
代码如下:
/*************************************************************************
> File Name: Balanced_Lineup.cpp
> Author: ZhangHaoRan
> Mail: [email protected]
> Created Time: 2016年07月14日 星期四 09时52分03秒
************************************************************************/
#include
#include
#include
#include
#include
#include
#include
#include
查看原文: http://chilumanxi.org/2016/07/27/%e6%b5%85%e8%b0%88rmq-st%e7%ae%97%e6%b3%95/