[BZOJ1345][Baltic2007]序列问题Sequence(单调栈)

来源:互联网 发布:mac book air13 101 编辑:程序博客网 时间:2024/04/27 23:29

题目描述

传送门

题解

维护栈低到栈顶单调递减的单调栈,每次进栈的时候都要考虑如何合并。

代码

#include<iostream>#include<cstring>#include<cstdio>using namespace std;#define LL long longconst int INF=2e9;int n,x,temp,strack[1000005];LL ans;int main(){    scanf("%d",&n);    strack[0]=INF;    for (int i=1;i<=n;++i){        scanf("%d",&x);        while (temp&&x>=strack[temp]){            if (x>=strack[temp-1]) ans+=(LL)strack[temp-1],temp--;            else ans+=(LL)x,temp--;        }        strack[++temp]=x;    }    while (temp>1) ans+=(LL)strack[--temp];    printf("%lld\n",ans);}
0 0
原创粉丝点击