【Patrik 音乐会的等待,洛谷P1823. [COI2007]】(单调栈)

题目

 思考

不论是单调栈还是单调队列,核心思想是保留有用的数据在数据结构中

上述问题,可以转化为a看向b的过程,在单调栈中,当a要加入栈中,就会比对top,这个时候,能够保证a与top之间的数比a和top小(反证法)

最后,需要单独处理下重复的问题

代码

#include<bits/stdc++.h>
using namespace std;
vector<int> a;
// first记录值,second记录数量
stack<pair<int,int>> st;
int main(){
    cin.tie(0);
    ios::sync_with_stdio(0);
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        int temp_a;
        cin>>temp_a;
        a.push_back(temp_a);
    }
    long long ans=0;
    for(int i=n-1;i>=0;i--){
        int temp=0;
        while(st.size()>0&&st.top().first<a[i])
            temp+=st.top().second,st.pop();
        int val=0;
        if(st.size()&&st.top().first==a[i]){
            val=st.top().second;
            temp+=val;
            st.pop();
        }
        if(st.size())
            temp++;
        ans+=temp;
        st.push({a[i],val+1});
    }
    cout<<ans<<'\n';
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值