Codeforces 821C Okabe and Boxes 题解

来源:互联网 发布:潘多拉克隆mac地址 编辑:程序博客网 时间:2024/04/24 16:28

题意

有两种操作,一种是将某个数字加入栈中,另一种是取栈顶数字,要求取出的数字顺序按1到n的顺序,给你一系列操作,你可以在任何一次操作后对栈中序列进行重排,可以排成任意顺序,问最少需要进行多少次重排才能满足条件

思路

重排肯定是排成小的在上大的在下的样子,我们不需要真的模拟,在遇到要重排的时候可以直接清空栈,而统计重排次数的时候只是在栈不为空且栈顶不是需要弹出的那个值的时候统计,并且清空

代码

#include <cstdio>#include <stack>using namespace std;char op[10];stack<int> st;int main(){    int n,ans,x,cnt;    scanf("%d",&n);    ans=0;    cnt=0;    for(int i=0;i<2*n;i++)    {        scanf("%s",op);        if(op[0]=='a')        {            scanf("%d",&x);            st.push(x);        }        else        {            cnt++;            if(!st.empty()&&st.top()==cnt)                st.pop();            else if(!st.empty())            {                ans++;                while(!st.empty())                    st.pop();            }        }    }    printf("%d\n",ans);    return 0;}
原创粉丝点击