[COI2007] Patrik 音乐会的等待 单调栈

Code:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<stack>
#include<string>
using namespace std;
void setIO(string a){ freopen((a+".in").c_str(),"r",stdin),freopen((a+".out").c_str(),"w",stdout); }
void shutIO(){fclose(stdin),fclose(stdout);}

#define maxn 500009
int val[maxn];
struct Node{
    int val,h;
    Node(int val=0,int h=0):val(val),h(h){}
};
stack<Node>S;
int main(){
    //setIO("wait");
    int n,a;
    long long ans=0;
    scanf("%d",&n);
    for(int i=1;i<=n;++i) scanf("%d",&val[i]);
    S.push(Node(1,val[1]));
    for(int i=2;i<=n;++i){
        a=0;
        while(!S.empty()&&S.top().h<val[i])ans+=S.top().val,S.pop();
        if(!S.empty()&&S.top().h==val[i]) a+=S.top().val,S.pop();
        ans+=a;
        ans+=(!S.empty());
        S.push(Node(a+1,val[i]));
    }
    printf("%lld",ans);
    //shutIO();
    return 0;
}

  

posted @ 2018-11-08 14:40  EM-LGH  阅读(141)  评论(0编辑  收藏  举报