Codeforces Round #420 C

Okabe and Boxes

题意:有2个操作,add x表示往栈里加入一个数x,remove表示从栈里拿出一个数,若要使得出栈的顺序为递增的,那么至少要对栈里面的元素进行多少次重新排序

思路:stack模拟栈,优先队列模拟出栈,每次记录当前最顶上的元素top,用来和当前出栈的数比较,如果不相等,则进行排序,并标记f表示已经是排好序的位置,若相等,则出栈,然后更新top,注意更新top的时候是取优先队列里的还是stack里的数,若当前的位置大于f,则取栈里的元素更新top,否则取优先队列里的数

AC代码:

#include "iostream"
#include "string.h"
#include "stack"
#include "queue"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "algorithm"
#include "stdio.h"
#include "math.h"
#define ll long long
#define bug(x) cout<<x<<" "<<"UUUUU"<<endl;
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
const int N=1e5+100;
priority_queue<int,vector<int>,greater<int> > Q;
int tot[3*N],t,p=1,ans,f,top;
char s[10];
int main(){
    int n,x;
    cin>>n;
    for(int i=1; i<=2*n; ++i){
        cin>>s;
        if(s[0]=='a'){
            cin>>x;
            Q.push(x);
            tot[++t]=x;
            top=x;
        }
        else{ //cout<<t<<" "<<f<<endl;cout<<top<<" "<<Q.top()<<endl;
            Q.pop();
            if(top==p){
                p++;t--;
                if(t>f){
                    top=tot[t];
                }
                else{
                    top=Q.top();
                    if(top==p) f--;
                }
            }
            else{  //cout<<"uuuu"<<endl;
                ans++;
                p++;
                top=Q.top();
                f=--t;
            }
        }
    }
    cout<<ans;
    return 0;
}
/*
3
add 1
remove
add 2
add 3
remove
remove
7
add 3
add 2
add 1
remove
add 4
remove
remove
remove
add 6
add 7
add 5
remove
remove
remove
6
add 3
add 4
add 5
add 1
add 6
remove
add 2
remove
remove
remove
remove
remove
7
add 4
add 6
add 1
add 5
add 7
remove
add 2
remove
add 3
remove
remove
remove
remove
remove
*/
原文地址:https://www.cnblogs.com/max88888888/p/7101846.html