题目地址:http://poj.org/problem?id=2559
思路:
方法一:设置一单调栈,栈中元素按高度依次递增。则对于新加入的元素,若当前高度大于栈顶元素高度,则直接入栈;否则,不断退栈直到栈顶元素高度小于当前元素高度(因前一高度已不能继续延续到当前高度)并将更新当前元素宽度,入栈。退栈过程中不断更新最大值:栈中元素(2,1),当前元素(1,1)此时退栈并且将退栈元素宽度累加作为当前元素宽度,则栈中元素变为(1,2);若栈中元素为(1,2)、(4,1)、(5,1),当前元素为(1,1),则退栈过程为(1,2)、(4,2);(1,4);(1,5)。若处理完后栈中元素不为空,按同样方法直到栈为空并不断更新最大值。
方法二:设置l[i]代表a[i]作为最小值向左最远的位置,r[i]代表a[i]作为最小值向右最远的位置。则ans=max{a[i]*(r[i]-l[i]+1)}。更新l[i]时,当a[l[i]-1]>=a[i]时,不断将l[i]置为l[l[i]-1];当a[r[i]+1]>=a[i]时,不断将r[i]置为r[r[i]+1]。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e5+50;
struct Node
{
int h,w;
};
int n;
Node S[maxn];
int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
int top=0;
LL ans=0;
for(int i=1;i<=n;i++)
{
int h,tmp=0;
scanf("%d",&h);
while(top>0&&S[top].h>=h)
{
ans=max(ans,(LL)S[top].h*(S[top].w+tmp));
tmp+=S[top].w;
top--;
}
top++,S[top].h=h;
S[top].w=tmp+1;
}
int tmp=0;
while(top)
{
ans=max(ans,(LL)S[top].h*(S[top].w+tmp));
tmp+=S[top].w;
top--;
}
printf("%lld\n",ans);
}
return 0;
}
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=1e5+50;
int n;
int l[maxn];
int r[maxn];
int a[maxn];
int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
l[i]=r[i]=i;
}
a[0]=a[n+1]=-1;
for(int i=1; i<=n; i++)
{
while(a[l[i]-1]>=a[i])
{
l[i]=l[l[i]-1];
}
}
for(int i=n; i>=1; i--)
{
while(a[r[i]+1]>=a[i])
{
r[i]=r[r[i]+1];
}
}
LL ans=0;
for(int i=1; i<=n; i++)
{
ans=max(ans,(LL)a[i]*(r[i]-l[i]+1));
}
printf("%lld\n",ans);
}
return 0;
}