傳送門
解題思路
從前往後維護一個嚴格單調遞減棧,在彈出元素和入棧的時候更新答案。
但是要注意兩人身高相等的情況,所以要記下某元素的個數。
細節還是蠻多的。
AC代碼
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<stack>
using namespace std;
const int maxn=5e5+5;
int n,a[maxn];
long long ans;
stack<pair<int,int> > q;
int main(){
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
while(!q.empty()&&a[q.top().first]<=a[i]){
if(a[q.top().first]==a[i]){
ans+=q.top().second;
q.top().second++;
if(q.size()>1) ans++;
break;
}
ans+=q.top().second;
q.pop();
}
if(!q.empty()){
if(a[q.top().first]==a[i]){
continue;
}
ans++;
}
q.push(make_pair(i,1));
}
cout<<ans;
return 0;
}