#420 Div.2 C. Okabe and Boxes——模拟

题目链接:
http://codeforces.com/contest/821/problem/C

大意:
对栈结构给出一串 add 和 remove 的命令,相当于 push 和 pop,现在要求 remove 的东西按照 1 2 3 … n的顺序取走,问需要在操作中最少改变几次 add 的顺序。

input
3
add 1
remove
add 2
add 3
remove
remove

output
1

input
7
add 3
add 2
add 1
remove
add 4
remove
remove
remove
add 6
add 7
add 5
remove
remove
remove

output
2

Note
In the first sample, Daru should reorder the boxes after adding box 3 to the stack.
In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.

分析:
模拟一直是自己的弱项,这道题明显是栈…可是自己走进歪路,原想算出正确 remove 和 add 的值 然后和题设的 input 比较,得出 ans 。但是发现比较很难实现。

正确做法是模拟栈的操作,当 remove 的东西不合要求时肯定要进行 1 次操作 。其次,重排后,栈可以清空,等待新的值加入。清空是因为后续的 remove 对于此栈来讲必然是可以实现的,当 add 新值时,栈已改变。

需要注意的是后续的 remove 对于此栈必然可以实现…因为如果不能实现那么说明你的调整不能让 remove 得到正确值题目就无解了…
看代码比较清楚。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mem(s,t) memset(s,t,sizeof(s))
#define D(v) cout<<#v<<" "<<v<<endl
#define inf 0x3f3f3f3f
const int N =3e5+10;

stack<int> a;

int main() {
#ifdef LOCAL
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif
    int n;
    scanf("%d",&n);
    int cnt=1,ans=0;
    for(int i=1;i<=2*n;i++){
        char s[10];
        scanf("%s",s);
        if(s[0]=='a'){
            int num;
            scanf("%d",&num);
            a.push(num);
        }else{
            if(a.empty());
            else if(a.top()==cnt){
                a.pop();
            }else{
                ans++;
                while(!a.empty()){
                a.pop();
                }
            }
            cnt++;
        }
    }
    printf("%d\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值