-
条件:适用于求区间最大值
-
题目:洛谷ST模板题
-
原理: 无
-
代码:
/** * mootable */ #include <iostream> #include <iomanip> #include <algorithm> //sort #include <map> #include <queue> #include <deque> //双端队列,头可插,尾可插 #include <string> #include <cstring> #include <stack> #include <cmath> #include <fstream> #include <ctime> #include <climits> //数值的限制范围 //(double)clock() / CLOCKS_PER_SEC <= 0.95 限制0.95s跑完 using namespace std; class Solver { //通用属性 public: Solver() { //取消和c输出输入的同步,加快读取 ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); } //通用方法 public: void SaveCpp(string name) const { fstream input; fstream output; input.open("moota.cpp", ios::in); const string file = name + ".cpp"; output.open(file.c_str(), ios::out); char c = 'O'; while (!input.eof()) { input.get(c); output << c; } input.close(); output.close(); } protected: //待实现方法 virtual void BeginPlay() { }; virtual void Playing() { }; virtual void EndPlay() { }; public: //外观模式 void Play() { BeginPlay(); Playing(); EndPlay(); } }; class SpecialSolver : public Solver { public: static const int MAX = static_cast<int>(1e6); static const long long INF = static_cast<long long>(1e18); private: //实例属性 int n, m; private: //实例方法 int maxValue[21][MAX];//数组i,j调换加快速度 int log2[MAX]; protected: virtual void BeginPlay() override { Solver::BeginPlay(); cin >> n >> m; for (int i = 1; i <= n; ++i) { cin >> maxValue[0][i]; } for (int j = 1; j <= 20; ++j) { for (int i = 1; (i + (1 << j) - 1) <= n; ++i) { maxValue[j][i] = max(maxValue[j - 1][i], maxValue[j - 1][i + (1 << (j - 1))]); } } for (int i = 2; i <= MAX; ++i) { log2[i] = log2[i / 2] + 1; } }; virtual void Playing() override { Solver::Playing(); int l, r; while (m--) { cin >> l >> r; int len = log2[r - l + 1]; cout << max(maxValue[len][l], maxValue[len][r - (1 << len) + 1]) << "\n"; } }; virtual void EndPlay() override { Solver::EndPlay(); }; }; SpecialSolver specialSolver; int main() { //注意改名字 specialSolver.Play(); //specialSolver.SaveCpp("ST表模板"); }
数据结构与算法-ST表模板
最新推荐文章于 2024-07-23 08:25:00 发布