update learn RMQ st

This commit is contained in:
Zengtudor 2024-08-07 15:46:28 +08:00
parent 06e93e15d8
commit 1770d113bd
5 changed files with 103 additions and 0 deletions

1
.gitignore vendored
View File

@ -52,3 +52,4 @@ day5/hard/hard
day5/perfect/perfect
day5/good/good
day5/fair/fair
day5/RMQ/st

View File

@ -71,6 +71,7 @@ ll ksm(ll a,ll b,ll M){
# [RMQ 区间最值问题](./day5/RMQ_by_chat.md)
>点击跳转
[自己手动实践](./day5/RMQ/st.cpp)
# 排序
## 稳定性

49
day5/RMQ/chat.cpp Normal file
View File

@ -0,0 +1,49 @@
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class SparseTable {
private:
vector<vector<int>> st;
vector<int> log;
int n;
public:
SparseTable(const vector<int>& arr) {
n = arr.size();
int K = log2(n) + 1;
st.assign(n, vector<int>(K));
log.assign(n + 1, 0);//为什么要n+1
// 初始化 log 数组
log[1] = 0;
for (int i = 2; i <= n; ++i) {
log[i] = log[i / 2] + 1;
}
// 初始化 st 数组
for (int i = 0; i < n; ++i) {
st[i][0] = arr[i];
}
// 动态规划填充 st 数组
for (int j = 1; j <= K; ++j) {
for (int i = 0; (i + (1 << j)) <= n; ++i) {
st[i][j] = min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);//为什么是j-1?
}
}
}
int query(int L, int R) {
int j = log[R - L + 1];
return min(st[L][j], st[R - (1 << j) + 1][j]);
}
};
int main() {
vector<int> arr = {1, 3, 5, 7, 9, 11};
SparseTable sparseTable(arr);
cout << "Min value in range [1, 4]: " << sparseTable.query(1, 4) << endl;
return 0;
}

45
day5/RMQ/st.cpp Normal file
View File

@ -0,0 +1,45 @@
#include<bits/stdc++.h>
using namespace std;
#define PRINT_VALUE(v){cout<<#v<<" :"<<v<<endl;}
struct SparseTable{
private:
vector<vector<int>> st;
vector<int> log;
int n;
public:
SparseTable(const vector<int> &arr){
n=arr.size();
int K=log2(n)+1;
st.assign(n,vector<int>(K));
log.assign(n+1,0);
log[1]=0;
for(int i=2;i<=n;i++){
log[i]=log[i/2]+1;
}
for(int i=0;i<n;i++){
st[i][0]=arr[i];
}
for(int j=1;j<=K;j++){
for(int i=0;(i+(1<<j))<=n;i++){
st[i][j]=min(st[i][j-1],st[i+(1<<(j-1))][j-1]);
}
}
}
int query(int l,int r){
int j=this->log[r-l+1];
return min(this->st[l][j],this->st[r-(1<<j)+1][j]);
//因为log[i]向下取整所以此时r>=(1<<j)求右边的区间就是st[]
}
};
int main(){
vector<int> v={1, 3, 5, 7, 9, 11};
SparseTable st_min(v);
// PRINT_VALUE(st_min.query(1,2));
PRINT_VALUE(st_min.query(1, 4));
}

7
day5/RMQ/st_raw.cpp Normal file
View File

@ -0,0 +1,7 @@
#include<bits/stdc++.h>
using namespace std;
int main(){
}