简单的栈
栈是一种后进先出的表,又称作 LIFO 表。
栈可以使用 STL。
using namespace std;
stack<int> stk;
stk.push(2); // push 2 into the stack
stk.top(); // return the top element of the stack
stk.pop(); // pop the element on the top of the stack out
stk.size(); // return the size of the stack
stk.empty(); // return whether the stack is empty
单调的栈
单调的栈叫单调栈。
单调栈中的元素具有(自顶向下的)单调性。
板子(来自于 luogu 5788 【模板】单调栈):
#include <bits/stdc++.h>
using namespace std;
stack<int> st;
int num[3000005];
int f[3000005];
int main()
{
int n;
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
scanf("%d",&num[i]);
}
for (int i=n;i>=1;i--)
{
while (!st.empty()&&num[st.top()]<=num[i])
{
st.pop();
}
f[i]=st.empty()?0:st.top();
st.push(i);
}
for (int i=1;i<=n;i++)
{
printf("%d ",f[i]);
}
return 0;
}
单调栈的(简单)应用
luogu 1901 发射站
这道题我们考虑使用单调递减的单调栈。
接着我们考虑插入一个新的元素的时候所发生的情况。
- 插入的新元素 x x x 满足单调性,则栈顶元素向 x x x 传送能量;
- 否则,依次弹出原单调栈中的部分元素,直到插入 x x x 后满足单调性即可,每一个被弹出的元素都要给 x x x 传送能量。
代码:
#include <bits/stdc++.h>
#define MAXN 1000005
using namespace std;
stack<int> stk;
int h[MAXN],v[MAXN],ans[MAXN];
int main()
{
int res=-1;
int n;
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
scanf("%d %d",&h[i],&v[i]);
}
for (int i=1;i<=n;i++)
{
while (!stk.empty()&&h[stk.top()]<h[i])
{
ans[i]+=v[stk.top()];
stk.pop();
}
if (!stk.empty())
{
ans[stk.top()]+=v[i];
}
stk.push(i);
}
for (int i=1;i<=n;i++)
{
res=max(res,ans[i]);
}
printf("%d\n",res);
return 0;
}
hdu 1506 最大子矩形
我们维护一个栈内元素单调递增的栈,在出栈时统计以栈顶高度为高的矩形面积来更新答案。
在每一个元素统计答案时,最右侧为
p
o
s
−
1
pos-1
pos−1,最左侧为出站后栈顶的位置
+
1
+1
+1。遍历一遍即可。
代码:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n;
while (scanf("%d",&n))
{
if (!n)
{
break;
}
vector<int> a(n);
for (int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
vector<int> fx(n),fy(n);
stack<int> stk1,stk2;
for (int i=0;i<n;i++)
{
while (!stk1.empty()&&a[stk1.top()]>=a[i])
{
stk1.pop();
}
if (stk1.empty())
{
fx[i]=0;
}
else
{
fx[i]=stk1.top()+1;
}
stk1.push(i);
}
for (int i=n-1;i>=0;i--)
{
while (!stk2.empty()&&a[stk2.top()]>=a[i])
{
stk2.pop();
}
if (stk2.empty())
{
fy[i]=n-1;
}
else
{
fy[i]=stk2.top()-1;
}
stk2.push(i);
}
long long ans=0;
for (int i=0;i<n;i++)
{
ans=max(ans,1ll*a[i]*(fy[i]-fx[i]+1));
}
printf("%lld\n",ans);
}
return 0;
}