给定一个栈(初始为空,元素类型为整数,且小于等于100),只有两个操作:入栈和出栈。先给出这些操作,请输出最终栈的栈顶元素。 操作解释:1表示入栈,2表示出栈
N(操作个数)
N个操作(如果是入栈则后面还会有一个入栈元素)
具体见样例(输入保证栈空时不会出栈)
最终栈顶元素,若最终栈空,输出”impossible!”(不含引号)
3
1 2
1 9
2
2
对于100%的数据 N≤1000 元素均为正整数且小于等于100
代碼實現:
手模
1 #include2 #include 3 using namespace std; 4 int stack[100],top,n,b,em; 5 int main(){ 6 cin>>n; 7 for(int i=0;i >b; 9 if(b==1){10 cin>>em;11 stack[top++]=em;12 }13 else top--;14 }15 if(!top) printf("impossible!\n");16 else cout< <
STL
1 #include2 #include 3 using namespace std; 4 stack st; 5 int a,b,n; 6 int main(){ 7 cin>>n; 8 for(int i=1;i<=n;i++){ 9 cin>>a;10 if(a==1){11 cin>>b;12 st.push(b);13 }14 if(a==2){15 if(st.empty()){cout<<"impossible!";return 0;}16 st.pop();17 }18 }19 if(!st.empty()) cout<
(此题与栈练习1相比改了2处:1加强了数据 2不保证栈空时不会出栈)
给定一个栈(初始为空,元素类型为整数,且小于等于100),只有两个操作:入栈和出栈。先给出这些操作,请输出最终栈的栈顶元素。 操作解释:1表示入栈,2表示出栈
N(操作个数)
N个操作(如果是入栈则后面还会有一个入栈元素)
具体见样例(输入不保证栈空时不会出栈)
最终栈顶元素,若最终栈空,或栈空时有出栈操作,输出”impossible!”(不含引号)
3
1 2
2
2
impossible!
对于100%的数据 N≤100000 元素均为正整数且小于等于10^8
代碼實現:
手模
1 #include2 #include 3 using namespace std; 4 int stack[100],top,n,b,em; 5 int main(){ 6 cin>>n; 7 for(int i=0;i >b; 9 if(b==1){10 cin>>em;11 stack[top++]=em;12 }13 else{14 if(!top){printf("impossible!\n");return 0;}15 top--;16 }17 }18 if(!top) printf("impossible!\n");19 else cout< <
STL
1 #include2 #include 3 using namespace std; 4 stack st; 5 int a,b,n; 6 int main(){ 7 cin>>n; 8 for(int i=1;i<=n;i++){ 9 cin>>a;10 if(a==1){11 cin>>b;12 st.push(b);13 }14 if(a==2){15 if(st.empty()){cout<<"impossible!";return 0;}16 st.pop();17 }18 }19 if(!st.empty()) cout<
比起第一题,本题加了另外一个操作,访问栈顶元素(编号3,保证访问栈顶元素时或出栈时栈不为空),现在给出这N此操作,输出结果。
N
N次操作(1入栈 2出栈 3访问栈顶)
K行(K为输入中询问的个数)每次的结果
6
1 7
3
2
1 9
1 7
3
7
7
对于50%的数据 N≤1000 入栈元素≤200
对于100%的数据 N≤100000入栈元素均为正整数且小于等于10^4
代碼實現:
手模
1 #include2 #include 3 using namespace std; 4 int stack[100],top,n,b,em; 5 int main(){ 6 cin>>n; 7 for(int i=0;i >b; 9 if(b==1){10 cin>>em;11 stack[top++]=em;12 }13 if(b==2){14 if(!top){printf("impossible!\n");return 0;}15 top--;16 }17 if(b==3) cout< <
STL
1 #include2 #include 3 using namespace std; 4 stack s; 5 int n,a,b; 6 int main(){ 7 cin>>n; 8 while(n--){ 9 cin>>a;10 if(a==1){11 cin>>b;12 s.push(b);13 }14 if(a==2) s.pop();15 if(a==3) cout< <
這麼水,感覺有點虛。
题目来源:CODE[VS]