-
条件:无
-
题目:洛谷单调栈模板题
-
原理:无
-
代码:
/* * Author: Moota * Copyright: Moota * Description: Written by Moota */ #include <iostream> //cin,cout #include <iomanip> //fixed<<setprecision(2) #include <algorithm> //sort #include <map> #include <queue> #include <stack> #include <deque> //双端队列,头可插,尾可插 #include <string> #include <cstring> #include <cmath> //sqrt,abs #include <fstream> //file #include <ctime> #include <climits> //数值极限 //(double)clock() / CLOCKS_PER_SEC <= 1 限制1s跑完程序 using namespace std; class Solver { public: Solver() { //取消和c输出输入的同步,加快读取 ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); //誓死捍卫c++的风格 } public: void SaveCpp(string name) const { fstream input; fstream output; input.open("moota.cpp", ios::in); output.open(name.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: typedef long long int lld; typedef unsigned long long int ulld; static const lld MAX = static_cast<lld>(1e7); static const lld INF = static_cast<lld>(1e18); private: //单调栈,就是一个栈,不过栈内元素保证单调性。即,栈内元素要么从小到大,要么从大到小。 //而单调栈维护的就是一个数前/后第一个大于/小于他的数。 int n; struct Node { int id; //编号 int value; //数值 }; //a是原数组,b是从原数组取出的元素 int a[MAX]; stack<Node> s; int res[MAX]; private: protected: virtual void BeginPlay() override { Solver::BeginPlay(); //注意修改文件名称 //SaveCpp("单调栈.cpp"); cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; } } virtual void Playing() override { Solver::Playing(); //a栈顶肯定是它之后最大的, //因为没有之后。 for (int i = n; i >= 1; --i) { while (!s.empty() && a[i] >= s.top().value) { s.pop(); } res[i] = s.empty() ? 0 : s.top().id; Node node = {i, a[i]}; s.push(node); } } virtual void EndPlay() override { Solver::EndPlay(); for (int i = 1; i <= n; ++i) { cout << res[i] << " "; } } }; static SpecialSolver specialSolver; int main() { specialSolver.Play(); return 0; }
数据结构与算法-单调栈
最新推荐文章于 2022-05-29 17:32:47 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)