洛谷 P1823 [COI2007] Patrik 音樂會的等待(單調棧)

傳送門


解題思路

從前往後維護一個嚴格單調遞減棧,在彈出元素和入棧的時候更新答案。
但是要注意兩人身高相等的情況,所以要記下某元素的個數。
細節還是蠻多的。

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章