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

来源:互联网 发布:centos打包iso文件 编辑:程序博客网 时间:2024/05/22 19:42

题目链接:
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 0x3f3f3f3fconst 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;}
原创粉丝点击