diff --git a/.gitignore b/.gitignore index 5b0dbe3..0dfe0f0 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,4 @@ day5/hard/hard day5/perfect/perfect day5/good/good day5/fair/fair +day5/RMQ/st diff --git a/README.md b/README.md index 81495d3..8c67b25 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ ll ksm(ll a,ll b,ll M){ # [RMQ 区间最值问题](./day5/RMQ_by_chat.md) >点击跳转 +[自己手动实践](./day5/RMQ/st.cpp) # 排序 ## 稳定性 diff --git a/day5/RMQ/chat.cpp b/day5/RMQ/chat.cpp new file mode 100644 index 0000000..5bcfb70 --- /dev/null +++ b/day5/RMQ/chat.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +using namespace std; + +class SparseTable { +private: + vector> st; + vector log; + int n; + +public: + SparseTable(const vector& arr) { + n = arr.size(); + int K = log2(n) + 1; + st.assign(n, vector(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 arr = {1, 3, 5, 7, 9, 11}; + SparseTable sparseTable(arr); + cout << "Min value in range [1, 4]: " << sparseTable.query(1, 4) << endl; + return 0; +} diff --git a/day5/RMQ/st.cpp b/day5/RMQ/st.cpp new file mode 100644 index 0000000..41c99d9 --- /dev/null +++ b/day5/RMQ/st.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +#define PRINT_VALUE(v){cout<<#v<<" :"<> st; + vector log; + int n; +public: + SparseTable(const vector &arr){ + n=arr.size(); + int K=log2(n)+1; + st.assign(n,vector(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;ilog[r-l+1]; + return min(this->st[l][j],this->st[r-(1<=(1< 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)); + +} + diff --git a/day5/RMQ/st_raw.cpp b/day5/RMQ/st_raw.cpp new file mode 100644 index 0000000..76b26b6 --- /dev/null +++ b/day5/RMQ/st_raw.cpp @@ -0,0 +1,7 @@ +#include +using namespace std; + + +int main(){ + +} \ No newline at end of file