poj2796(单调栈)

http://poj.org/problem?id=2796

确定每个数边界,然后枚举

#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std;
#define ll long long
const int maxn=1e5+10;
int L[maxn],R[maxn],a[maxn],n,l,r;
ll pre[maxn],ans=-1;
stack<int>sta;

int main()
{
    scanf("%d",&n);
    a[0]=-1;
    a[n+1]=-1;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),pre[i]=pre[i-1]+a[i];
    for(int i=1;i<=n+1;i++)
    {
        if(sta.empty()||a[i]>=a[sta.top()])
            sta.push(i);
        else
        {
            while(!sta.empty()&&a[i]<a[sta.top()])
            {
                R[sta.top()]=i-1;
                sta.pop();
            }
            sta.push(i);
        }
    }
    sta.pop();
    for(int i=n;i>=0;i--)
    {
        if(sta.empty()||a[i]>=a[sta.top()])
            sta.push(i);
        else
        {
            while(!sta.empty()&&a[i]<a[sta.top()])
            {
                L[sta.top()]=i+1;
                sta.pop();
            }
            sta.push(i);
        }
    }
    for(int i=1;i<=n;i++)
    {
        if((pre[R[i]]-pre[L[i]-1])*a[i]>ans)
            ans=(pre[R[i]]-pre[L[i]-1])*a[i],l=L[i],r=R[i];
    }
    printf("%lld\n%d %d",ans,l,r);
    return 0;
}

 

posted @ 2019-04-23 22:41  eason99  阅读(66)  评论(0编辑  收藏  举报