• 洛谷 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;
    }
    
  • 相关阅读:
    猜数字游戏
    发红包程序
    实现微信摇一摇部分功能
    计算1+1/2+1/3+....+1/100的值
    约瑟夫问题
    简易计时器
    简易学生管理系统
    文件加密解密
    分鱼问题
    分橘子问题
  • 原文地址:https://www.cnblogs.com/yinyuqin/p/15129847.html
Copyright © 2020-2023  润新知