算法训练 表达式计算
来源:互联网 发布:淘宝助理官方下载 免费 编辑:程序博客网 时间:2024/05/17 22:17
问题描述 输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。输入格式 输入一行,包含一个表达式。输出格式 输出这个表达式的值。样例输入1-2+3*(4-5)样例输出-4数据规模和约定 表达式长度不超过100,表达式运算合法且运算过程都在int内进行。
//把中缀表达式转换成后缀表达式,然后从左到右扫描一遍即可,//扫描时可另设一个栈,如遇符号出两个数并计算后将结果入栈 #include<cstdio>#include<iostream>#include<cstring>using namespace std;const int maxn=120;char s[maxn];int cmp[500];//把符号打表,方便比较优先级void init(){cmp['+']=cmp['-']=1;cmp['*']=cmp['/']=2;}int calculate(int t,int t1,int t2){if(t=='+') return t1+t2;if(t=='-') return t1-t2;if(t=='*') return t1*t2; return t1/t2;}int solve(){int i=0,len=strlen(s),c[maxn];//c为符号栈int vis[maxn]={0};//判断该位是不是符号int suffix[maxn];//存储后缀表达式的栈 int t,top=0,tops=0;while(i<len){if(s[i]>='0'&&s[i]<='9'){int t=s[i++]-'0';while(s[i]>='0'&&s[i]<='9'){t=t*10+s[i++]-'0';}suffix[tops++]=t;}else{switch(s[i]){case '(':c[top++]=s[i];break;case ')':while(top>0&&c[top-1]!='('){vis[tops]=1;suffix[tops++]=c[--top];}top--; break;default:while(top>0&&c[top-1]!='('&&cmp[c[top-1]]>=cmp[s[i]]){vis[tops]=1;suffix[tops++]=c[--top];}c[top++]=s[i];}i++;}}while(top>0){vis[tops]=1;suffix[tops++]=c[--top];}//此时后缀表达式已找到,再临时利用一个栈即可算出结果for(int i=0;i<tops;i++){if(!vis[i]) c[top++]=suffix[i];else{c[top-2]=calculate(suffix[i],c[top-2],c[top-1]);top--;}}return c[0];}int main(){init();scanf("%s",s);cout<<solve()<<endl;return 0;}
1 0
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 算法训练 表达式计算
- 蓝桥杯算法训练 表达式计算
- 蓝桥杯--算法训练 表达式计算
- 蓝桥杯 算法训练 表达式计算
- 蓝桥杯 算法训练-表达式计算
- 蓝桥杯 算法训练 表达式计算
- 蓝桥杯 算法训练 表达式计算
- 算法训练 表达式计算 ——蓝桥杯
- andriod 安装apk报错:[INSTALL_PARSE_FAILED_NO_CERTIFICATES]
- configure: WARNING: sys/capability.h: accepted by the compiler, rejected by the preprocessor!
- Java-Stack实现中序表达式求值
- Runnable , Callable 区别
- 【Bug日常】 Admin(表名)is not mapped
- 算法训练 表达式计算
- 40. Combination Sum II Medium
- 2017年4月21日 计算机技术动态
- postgre sql 学习
- Mac上安装MySQL后在终端连接不上数据库Command not found
- HDOJ--2037 今年暑假不AC
- C# 正则表达式
- 5天学会jaxws-webservice编程
- Qt学习之路-贪吃蛇