最近刷洛谷刷到rmq,发现不会维护区间最值操作,学习一下。
目录
rmq(Range Maximum/Minimum Query)
rmq(Range Maximum/Minimum Query)
rmq主要是求区间的最大值或最小值一类的问题。首先最先想到的暴力就是遍历区间求最大最小值,但这只适用于小范围数据,当数据范围较大时,就可以用st表,利用倍增的思想来优化这一过程。
ST表
ST 表基于倍增思想,可以做到预处理,回答每个询问。但是不支持修改操作。于是我们用来表示从当前下标开始,长度为的区间的最值,于是基于dp的思想我们先初始化,即长度为1的区间。于是根据倍增思想就能写出状态转移方程:,最小值同理。于是便有以下模版题:
洛谷P2880
题目描述
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 ≤ 180,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.
每天,农夫 John 的 n(1≤n≤5×104) 头牛总是按同一序列排队。
有一天, John 决定让一些牛们玩一场飞盘比赛。他准备找一群在队列中位置连续的牛来进行比赛。但是为了避免水平悬殊,牛的身高不应该相差太大。John 准备了 q(1≤q≤1.8×105) 个可能的牛的选择和所有牛的身高 hi(1≤hi≤106,1≤i≤n)。他想知道每一组里面最高和最低的牛的身高差。
输入格式
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.
第一行两个数 n,q。
接下来 n 行,每行一个数 hi。
再接下来 q行,每行两个整数 a 和 b,表示询问第 a 头牛到第 b 头牛里的最高和最低的牛的身高差。
输出格式
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.
输出共 q 行,对于每一组询问,输出每一组中最高和最低的牛的身高差。
#include<iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <stack>
#include <unordered_map>
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
typedef pair<int, int> PII;
const int mod = 998244353;
const int N = 31;
const int M=5e4+10;
const int inf = 0x3f3f3f3f;
LL gcd(LL a, LL b)
{
return b ? gcd(b, a % b) : a;
}
void solve()
{
int f1[M][N],f2[M][N];
int n,q;
cin>>n>>q;
int x;
for(int i=1;i<=n;i++) {
cin>>x;
f1[i][0]=f2[i][0]=x;//初始化
}
for(int i=1;1<<i<=n;i++){//枚举区间长度
for(int j=1;j+(1<<i)-1<=n;j++){//枚举起点
f1[j][i]=max(f1[j][i-1],f1[j+(1<<(i-1))][i-1]);//状态转移
f2[j][i]=min(f2[j][i-1],f2[j+(1<<(i-1))][i-1]);
}
}
while(q--){
int l,r,k;
cin>>l>>r;
k=log2(r-l+1);
cout<<max(f1[l][k],f1[r-(1<<k)+1][k])-min(f2[l][k],f2[r-(1<<k)+1][k])<<'\n';//o(1)查询
}
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0),cout.tie(0);
solve();
}
这题是综合了最大值和最小值,P1816忠诚也是一道ST表模版题,也可以做做巩固一下。