作用: 可以很方便地求出 某个数的左边或者右边 第一个比它大或者小的元素
实现: 当栈顶元素比要进栈的元素大,则弹出 (单调递增栈)
直到栈顶元素比他小为止
进栈
来源:https://user.qzone.qq.com/50222268/blog/1497969740
代码:
注意范围!!!
#include <cstdio>
#include <algorithm>
#include <stack>
using namespace std;
struct node
{
long long h,wz;
};
const int maxSize=100000;
int n;
long long smax=0;
long long a[maxSize+5];
stack <node> s;
void dandiao()
{
int i,j;
node n1,n2;
n1.h=-1; n1.wz=0;
s.push(n1);
smax=0;
for (i=1;i<=n;i++)
{
n1=s.top();
if (a[i]>n1.h) //符合单调
{
n2.h=a[i]; n2.wz=i;
s.push(n2);
}
else if (a[i]==n1.h)
continue;
else //不符合
{
while (a[i]<=n1.h) //弹出所有比当前这数小的点
{
s.pop();
smax=max(smax,n1.h*(i-n1.wz)); //计算面积
j=n1.wz;
n1=s.top();
}
n2.h=a[i]; n2.wz=j; //进栈
s.push(n2);
}
}
n1=s.top();
while (n1.wz!=0)
{
smax=max(smax,n1.h*(i-n1.wz));
s.pop();
n1=s.top();
}
s.pop();
printf("%lld\n",smax);
}
int main()
{
int i;
freopen("a.txt","r",stdin);
while (1)
{
scanf("%d",&n);
if (n==0)
break;
for (i=1;i<=n;i++)
scanf("%d",&a[i]);
dandiao();
}
return 0;
}