单调栈刷题
文章目录
- bitset
- 单调栈
- 题解
- 代码
bitset
1. 有很多位的二进制数
2. 支持位运算
3. 不支持加减乘除
单调栈
题解
1. 7 8 5 6 7 ,栈为空,栈中只有一个数没有数比它小,l[i] = -1,栈不为空,如果有数小于它,l[i] = a[i]
2. 栈不为空,满足两个条件,如果两数大小相等,选择较近的那个数,左边的数要出栈,比如 2 6 6,相等的不能要,选择小于6的数
代码
用STL栈的做法
#include<iostream>
#include<stack>
using namespace std;
const int N = 2e5 + 10;
int a[N],l[N];
int main()
{
stack<int> st;
int n;
cin >> n;
for(int i = 0;i < n;i++) cin >> a[i];
for(int i = 0;i < n;i++)
{
while(st.size() && st.top() >= a[i]) st.pop();
// 1.栈为空
if(st.empty()) l[i] = -1;
// 2.栈不为空
if(!st.empty() && st.top() < a[i])
l[i] = st.top();
st.push(a[i]);
}
for(int i = 0;i < n;i++) cout << l[i] << " ";
return 0;
}
用数组模拟栈
#include<iostream>
#include<stack>
using namespace std;
// 用数组模拟栈
const int N = 2e5 + 10;
int a[N],l[N],st[N],top;
int main()
{
int n;
cin >> n;
for(int i = 0;i < n;i++) cin >> a[i];
for(int i = 0;i < n;i++)
{
while(top && a[st[top]] >= a[i]) top--;
// 在栈中的数比a[i] 大的都出掉了
if(top) l[i] = a[st[top]];
else l[i] = -1;
st[++top] = i;
// 把下次栈中的下标存好
}
for(int i = 0;i < n;i++) cout << l[i] << " ";
return 0;
}