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

题目描述

传送门

题解

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

代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define LL long long
const 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);
}

你可能感兴趣的:(单调栈,bzoj)