洛谷 P3467 [POI2008]PLA-Postering(单调栈)

传送门


解题思路

可以举例观察得到:131这种结构可以省去一次,而313不行。
所以就用单调栈维护一个自栈顶到栈底严格递减栈,每次若栈顶大于a[i],则栈顶出栈并且ans++,若相等则出栈并且ans不变。
可以把a[n+1]设置为0.(即最后让所有元素出栈)

AC代码

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<iomanip>
#include<ctime>
#include<stack>
using namespace std;
int n,x,ans; 
stack<int> s;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<=n;i++){
    	cin>>x;
    	cin>>x;
    	while(!s.empty()&&s.top()>x) s.pop(),ans++;
    	while(!s.empty()&&s.top()==x) s.pop();
    	s.push(x);
	}
	while(!s.empty()) s.pop(),ans++;
	cout<<ans;
    return 0;
}
posted @ 2021-08-11 19:06  尹昱钦  阅读(65)  评论(0编辑  收藏  举报