#420 Div2 C

#420 Div2 C

题意

不断把数加入到一个栈里,取数的时候要求按照 1~n 的顺序取数,每次取数保证数一定在栈里,如果要取的数不在栈头,可以选择对栈排序一次。问最少排序几次。

分析

只要栈头的数不符合条件,就要去排序,但是不能直接去模拟。不用真的去排序,可以选择直接清空栈,只要没有新数加进来,后面的所有取数的操作一定是符合条件的(因为每次取数时保证数一定在栈内),如果有新数加进来,若正好符合条件,直接取它即可,否则清空栈。

code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, cnt = 0;
    cin >> n;
    stack<int> sta;
    int tp = 1;
    for(int i = 0; i < 2 * n; i++) {
        string s;
        cin >> s;
        if(s == "add") {
            int one;
            cin >> one;
            sta.push(one);
        } else {
            if(!sta.empty()) {
                if(sta.top() != tp) {
                    while(!sta.empty()) sta.pop();
                    cnt++;
                } else {
                    sta.pop();
                }
            }
            tp++;
        }
    }
    cout << cnt << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/ftae/p/7095745.html