学习笔记::单调栈

单调栈和单调队列长得不是很像。

单调栈的用处是求以一个元素为中心,向两边最多拓展多远距离。

两个小时就没了。。。

poj2796

#include<cstdio>
using namespace std;
typedef long long ll;
#define N 200010
struct data
{
    ll v,sum,l,r;
}x[N],st[N],ans;
ll n;
inline void read(ll&a)
{
    ll x=0,f=1; char c=getchar();
    while(c<'0'||c>'9') {if(c=='-') f=-1; c=getchar(); }
    while(c>='0'&&c<='9') {x*=10; x+=c-'0'; c=getchar(); }
    a=x*f;
}
int main()
{
    read(n);
    for(int i=1;i<=n;++i) read(x[i].v),x[i].sum=x[i].v,x[i].r=x[i].l=i;
    int top=0;
    for(int i=1;i<=n;++i)
    {
        while(top&&x[i].v<=st[top].v)
        {
            if(st[top].v*st[top].sum>ans.v)
            {
                ans.v=st[top].v*st[top].sum;
                ans.l=st[top].l;
                ans.r=st[top].r;
            }
            if(top>1&&x[i].v<=st[top-1].v) 
            {
                st[top-1].sum+=st[top].sum;
                st[top-1].r=st[top].r;
            }            
            if(st[top-1].v<x[i].v) 
            {
                x[i].sum+=st[top].sum;
                x[i].l=st[top].l;
            }
            --top;
        }
        st[++top]=x[i];        
    }
    while(top>=0)
    {
        if(st[top].v*st[top].sum>ans.v)
        {
            ans.v=st[top].v*st[top].sum;
            ans.l=st[top].l;
            ans.r=st[top].r;
        }
        st[top-1].sum+=st[top].sum;
        st[top-1].r=st[top--].r;
    }
    if(ans.l==0) ans.l=ans.r=1;
    printf("%lld\n%lld %lld\n",ans.v,ans.l,ans.r);
    return 0;
}
View Code

 

posted @ 2017-02-12 00:00  19992147  阅读(175)  评论(0编辑  收藏  举报