题目1108:堆栈的使用
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:11671
解决:3392
题目描述:
堆栈是一种基本的数据结构。堆栈具有两种基本操作方式,push 和 pop。Push一个值会将其压入栈顶,而 pop 则会将栈顶的值弹出。现在我们就来验证一下堆栈的使用。
- 输入:
-
对于每组测试数据,第一行是一个正整数 n,0<n<=10000(n=0 结束)。而后的 n 行,每行的第一个字符可能是'P’或者'O’或者'A’;如果是'P’,后面还会跟着一个整数,表示把这个数据压入堆栈;如果是'O’,表示将栈顶的值 pop 出来,如果堆栈中没有元素时,忽略本次操作;如果是'A’,表示询问当前栈顶的值,如果当时栈为空,则输出'E'。堆栈开始为空。
- 输出:
-
对于每组测试数据,根据其中的命令字符来处理堆栈;并对所有的'A’操作,输出当时栈顶的值,每个占据一行,如果当时栈为空,则输出'E’。当每组测试数据完成后,输出一个空行。
- 样例输入:
-
3 A P 5 A 4 P 3 P 6 O A 0
- 样例输出:
-
E 5 3
#include<stdio.h> #include<stack> #include<cstring> using namespace std; int main(){ int n; stack<int> ch; while(scanf("%d",&n)!=EOF&&n!=0){ // getchar(); while(!ch.empty()) ch.pop(); while(n--!=0){ char c[4]; scanf("%s",c);//这里原本是使用gets来读取字符串的,它与scanf的区别就是可以接受空格、TAB等制表符 , //如果用gets,P操作需要压栈 的数字也会被读入字符串,不如直接用scanf处理来的方便 if(c[0]=='A'){ // if(ch.empty()){ // printf("go1\n");} // if(!ch.empty()){ // printf("go2\n");} if(!ch.empty()){ // printf("go!\n"); printf("%d\n",ch.top()); } else printf("E\n"); } else if(c[0]=='O'){ if(!ch.empty()){ ch.pop(); } } else if(c[0]=='P'){ int a; scanf("%d",&a); // if(c[2]=='5') // printf("ding!\n"); // else // printf("%c\n",c[2]); ch.push(a); } } printf("\n"); } return 0; }
题目1101:计算表达式
时间限制:1 秒
内存限制:32 兆
特殊判题:否
扫描二维码关注公众号,回复:
139720 查看本文章
提交:7388
解决:2307
- 题目描述:
-
对于一个不存在括号的表达式进行计算
- 输入:
-
存在多种数据,每组数据一行,表达式不存在空格
- 输出:
-
输出结果
- 样例输入:
-
6/2+3+3*4
- 样例输出:
-
18
#include<stack> #include<cstdio> #include<iostream> using namespace std; stack<int> op; stack<double> in; int mat[][5]={ 1,0,0,0,0, 1,0,0,0,0, 1,0,0,0,0, 1,1,1,0,0, 1,1,1,0,0, }; char str[1000]; void getE(double &retn,int &i,bool &reto){ if(i==0&&op.empty()==true){ reto=true; retn=0; return; } if(str[i]==0){ reto=true; retn=0; return; } if(str[i]>='0'&&str[i]<='9'){ reto=false; } else{ reto=true; if(str[i]=='+') retn=1; if(str[i]=='-') retn=2; if(str[i]=='*') retn=3; if(str[i]=='/') retn=4; i++; return; } retn=0; for(;str[i]<='9'&&str[i]>='0'&&str[i]!=0;i++){ retn*=10; retn+=str[i]-'0'; } double d=1,dd=0; if(str[i]=='.'){ i++; for(;str[i]<='9'&&str[i]>='0';i++){ d/=10; dd+=(str[i]-'0')*d; } } retn+=dd; return; } int main(){ while(scanf("%s",str)!=EOF){ while(!op.empty()) op.pop(); while(!in.empty()) in.pop(); double ren; int index=0; bool reop; while(true){ getE(ren,index,reop); if(reop==false){ in.push(ren); } else{ if(op.empty()==true||mat[(int)ren][op.top()]==1) op.push(ren); else{ while(mat[(int)ren][op.top()]==0){ int o; o=op.top(); op.pop(); double b=in.top(); in.pop(); double a=in.top(); in.pop(); if(o==1) a=a+b; else if(o==2) a=a-b; else if(o==3) a=a*b; else if(o==4) a=a/b; in.push(a); } op.push(ren); } } if(op.size()==2&&op.top()==0) break; } cout<<in.top()<<endl; } return 0; } //1+3/2-1*3