3137 栈练习1

3137 栈练习1

 

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold
 
 
 
题目描述 Description

给定一个栈(初始为空,元素类型为整数,且小于等于100),只有两个操作:入栈和出栈。先给出这些操作,请输出最终栈的栈顶元素。  操作解释:1表示入栈,2表示出栈

输入描述 Input Description

N(操作个数)

N个操作(如果是入栈则后面还会有一个入栈元素)

具体见样例(输入保证栈空时不会出栈)

输出描述 Output Description

最终栈顶元素,若最终栈空,输出”impossible!”(不含引号)

样例输入 Sample Input

3

1 2

1 9

2

样例输出 Sample Output

2

数据范围及提示 Data Size & Hint

对于100%的数据  N≤1000 元素均为正整数且小于等于100

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<string>
 4 #include<cstring>
 5 #include<iostream>
 6 using namespace std;
 7 int a[10000];
 8 int b[10000];
 9 int st[10000];
10 int main()
11 {
12     int n;
13     cin>>n;
14     for(int i=1;i<=n;i++)
15      {
16          cin>>a[i];
17          if(a[i]==1)
18           {
19               cin>>b[i];
20           }
21       } 
22 
23      int top=0;
24      for(int i=1;i<=n;i++)
25       {
26           if(a[i]==1)
27            {
28                top++;
29                st[top]=b[i];
30            }
31           if(a[i]==2)
32            {
33                top--;
34             } 
35        } 
36        if(top<=0)
37         {
38             cout<<"impossible!";
39             return 0;
40         }
41          else cout<<st[top]; 
42       
43       return 0;
44 }
原文地址:https://www.cnblogs.com/lyqlyq/p/6628907.html