题目
思考
不论是单调栈还是单调队列,核心思想是保留有用的数据在数据结构中
上述问题,可以转化为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;
}