2.滚珠桶(barrel.cpp)
【问题描述】
在一个长方形空桶中,我们可以往里放彩色珠子,分别用 1,2,3 代表它们的颜色。
具体操作为 n 步,每一步为:动作+颜色或者只有动 作,如:put 1(中间空一格)表示放入一枚颜 色为 1 的珠子(每次只放一枚),take 则表示取出最上面的珠子,如果桶为空,则忽略本次 操作。请你处理,并按序号 1,2,3 的顺序输出最后桶中的三种珠子个数。
【输入格式】输入文件名为 barrel.in。
第 1 行 1 个正整数 n。
以下是 n 行,每行一个操作。格式如上。
【输出格式】输出文件名为 barrel.out。
输出为三行,表示每种珠子的个数;
【输入输出样例 1】
barrel.in
4
put 2
put 1
take
put 2
barrel.out
0
2
0
【样例说明】
put 2:放入 2 号珠子一个;put 1:放入 1 号珠子一 个;take:拿出最上面的 1 号珠子,put 2 :再放入 2 号珠子一个,最后珠桶里有 1 号 0 枚,2 号 2 枚,3 号 0 枚。
【输入输出样例 2】
barrel.in
7
take
3
put 1
put 1
take
put 2
take
take
barrel.out
0
0
0
我的代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
string op;
int n,color,m;
int cnt1,cnt2,cnt3;
stack<int>st;
int main(){
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
cin>>n;
for(int i=1;i<=n;i++){
cin>>op;
if(op=="put"){
cin>>color;
st.push(color);
m=color;
if(color==1){
cnt1++;
}else if(color==2){
cnt2++;
}else{
cnt3++;
}
}
if(op=="take"&&st.empty()){
continue;
}
if(op=="take"){
st.pop();
if(m==1){
cnt1--;
}else if(m==2){
cnt2--;
}else{
cnt3--;
}
}
}
cout<<cnt1<<endl<<cnt2<<endl<<cnt3<<endl;
return 0;
}
样例2输出:1,-1,0,大佬来帮帮忙吧