单调栈可以用来是实现在 离线的情况下,O(n)的处理出数组中所有点比某个点小或大最近的距离是多少;
具体做法是用栈来维护一边的点的下表,由于假如i<j hi>hj 那么h【i】便永无出头之日;可以把他删了,而在栈里能找到的直到第一次出现的小与hi的h【j】就一定是最近的,每个点出栈一次,进栈一次,所以时间复杂度是on的;
例题是acwing 131和152
以下给出ac代码:
栈没有用stl而是数组模拟是因为数组模拟快很多
```
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+7;
int h[maxn],l[maxn],r[maxn];
int n;
void get(int a[]){
int stk[maxn],cnt=0;
stk[0]=0;
for(int i=1;i<=n;i++){
while(h[stk[cnt]]>=h[i])cnt--;
a[i]=stk[cnt],stk[++cnt]=i;
}
}
int main()
{
h[0]=-1;
while(~scanf("%d",&n)&&n){
for(int i=1;i<=n;i++)scanf("%d",&h[i]);
get(l);
reverse(h+1,h+1+n);
get(r);
ll res=0;
for(int i=1;i<=n;i++)res=max(res,(ll)h[i]*(n-r[i]-l[n+1-i]));
printf("%lld\n",res);
}
return 0;
}
```
```
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn=1010;
int h[maxn][maxn],l[maxn],r[maxn],stk[maxn],top;
int n,m;
void get(int a[],int h[]){
stk[0]=0,h[0]=-1,top=0;
for(int i=1;i<=m;i++){
while(h[stk[top]]>=h[i])top--;
a[i]=stk[top];stk[++top]=i;
}
}
int work(int a[]){
get(l,a);
reverse(a+1,a+1+m);
get(r,a);
int res=0;
for(int i=1;i<=m;i++)res=max(res,a[i]*(m-r[i]-l[m+1-i]));
return res;
}
int main()
{
char c[5];
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%s",&c);
if(c[0]=='F')h[i][j]=h[i-1][j]+1;
else h[i][j]=0;
}
}
int res=0;
for(int i=1;i<=n;i++)res=max(res,work(h[i]));
printf("%d\n",res*3);
return 0;
}
```