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
#include<iostream> #include<cstring> #include<cstdio> using namespace std; int tack[1200],top,x,y,n; int main() { scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&x); if(x==1){ scanf("%d",&y); tack[++top]=y; } else top--; } if(top>=1) printf("%d",tack[top]); else printf("impossible!"); return 0; }
3138 栈练习2
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 黄金 Gold
题目描述 Description
(此题与栈练习1相比改了2处:1加强了数据 2不保证栈空时不会出栈)
给定一个栈(初始为空,元素类型为整数,且小于等于100),只有两个操作:入栈和出栈。先给出这些操作,请输出最终栈的栈顶元素。 操作解释:1表示入栈,2表示出栈
输入描述 Input Description
N(操作个数)
N个操作(如果是入栈则后面还会有一个入栈元素)
具体见样例(输入不保证栈空时不会出栈)
输出描述 Output Description
最终栈顶元素,若最终栈空,或栈空时有出栈操作,输出”impossible!”(不含引号)
样例输入 Sample Input
3
1 2
2
2
样例输出 Sample Output
impossible!
数据范围及提示 Data Size & Hint
对于100%的数据 N≤100000 元素均为正整数且小于等于10^8
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 int tack[1200000],top,x,y,n; 6 int main() 7 { 8 scanf("%d",&n); 9 for(int i=1;i<=n;i++){ 10 scanf("%d",&x); 11 if(x==1){ 12 scanf("%d",&y); 13 tack[++top]=y; 14 } 15 else { 16 if(top>=1) top--; 17 else { 18 printf("impossible!\n");return 0; 19 } 20 } 21 } 22 if(top>=1) printf("%d",tack[top]); 23 else printf("impossible!"); 24 25 return 0; 26 }
3139 栈练习3
时间限制: 2 s 空间限制: 128000 KB 题目等级 : 黄金 Gold
题目描述 Description
比起第一题,本题加了另外一个操作,访问栈顶元素(编号3,保证访问栈顶元素时或出栈时栈不为空),现在给出这N此操作,输出结果。
输入描述 Input Description
N
N次操作(1入栈 2出栈 3访问栈顶)
输出描述 Output Description
K行(K为输入中询问的个数)每次的结果
样例输入 Sample Input
6
1 7
3
2
1 9
1 7
3
样例输出 Sample Output
7
7
数据范围及提示 Data Size & Hint
对于50%的数据 N≤1000 入栈元素≤200
对于100%的数据 N≤100000入栈元素均为正整数且小于等于10^4
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 int tack[1200000],top,x,y,n; 6 int main() 7 { 8 scanf("%d",&n); 9 for(int i=1;i<=n;i++){ 10 scanf("%d",&x); 11 if(x==1){ 12 scanf("%d",&y); 13 tack[++top]=y; 14 } 15 if(x==2) top--; 16 if(x==3) printf("%d\n",tack[top]); 17 } 18 return 0; 19 }