11.3号算法
模拟栈
模拟栈
push x :栈顶所在索引往后移动一格,然后放入x。st[++top] = x。
pop : top 往前移动一格。top–。
empty :top 大于等于 0 栈非空,小于 0 栈空。top == -1 ? “YES” : “NO”
实现初始化top=-1对栈进行初始化,表示空
实现压栈和出栈压栈 需要++top 然后读入即可 stk[++top]=x,出栈 只需 --top
#include <iostream>
using namespace std;
const int N = 100010;
int st[N];
int top = -1;
int n;
int main()
{
cin >> n;
while(n--)
{
string s;
cin >> s;
//栈顶所在索引往后移动一格,然后放入x。
if(s == "push")
{
int a;
cin >> a;
st[++top] = a;
}
//往前移动一格
if(s == "pop")
{
top --;
}
//返回栈顶元素
if(s == "query")
{
cout << st[top] << endl;
}
//大于等于 0 栈非空,小于 0 栈空
if(s == "empty")
{
cout << (top == -1 ? "YES" : "NO") << endl;
}
}
}
单调栈
#include <iostream>
using namespace std;
const int N = 100010;
int stk[N], tt;
int main()
{
int n;
cin >> n;
while (n -- )
{
int x;
scanf("%d", &x);
while (tt && stk[tt] >= x) tt -- ;//如果栈顶元素大于当前待入栈元素,则出栈
if (!tt) printf("-1 ");//如果栈空,则没有比该元素小的值。
else printf("%d ", stk[tt]);//栈顶元素就是左侧第一个比它小的元素。
stk[ ++ tt] = x;
}
return 0;
}
使用c++stl的代码,全程引用大佬
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n,x;
cin >> n;
vector<int> t;
while (n--) {
cin >> x;
while (t.size() > 0 and t.back() >= x) {
t.pop_back();