WOJ1211-表达式的值

来源:互联网 发布:淘宝商品信用卡套现 编辑:程序博客网 时间:2024/06/06 00:19

如果给你一个只包含+,-,*,/,(,),及非负整数数字和空格组成的字符串表达式,你能编程计算它的值吗?

输入格式

第一行为一个N,表示测试样例数。 以下N行每个样例为一个字符串表达式,每个表达式至少一个字符,可能包含空格,但长度不超过50.

输出格式

对每一测试样例,输出它的值。

样例输入

3(2+3/3)+12+1/2-510*(2-2 )

样例输出

4-30


#include<iostream>#include<string>#include<stack>using namespace std;//进行计算,a@b,其中@是操作符,由c表示,可以是加减乘除,a和b分别是操作数int calculate(int a,int b,int c) {switch(c) {case 0:return a+b;case 1:return a-b;case 2:return a*b;case 3:return a/b;}}//进行字符确认,看其是何种操作符号 ,注意针对空格的处理int certify(char c) {switch(c) {case ' ':return 7;case '=':return 6;case ')':return 5;case '(':return 4;case '/':return 3;case '*':return 2;case '-':return 1;case '+':return 0;default :return 8;}}//在确认了字符不是空格或者操作符号的时候就知道它是数字了,所以进行转换int gdata(char c) {switch(c) {case '0':return 0;case '1':return 1;case '2':return 2;case '3':return 3;case '4':return 4;case '5':return 5;case '6':return 6;case '7':return 7;case '8':return 8;case '9':return 9;}}int main() {char scs[51];string s;//这个矩阵是优先级矩阵,就是当当前符号是…的时候下一符号对比,0表示小于,1表示大于,2表示等于,3表示错误//于是,0的时候符号入栈,1的时候进行计算,2的时候出栈,3的时候就该报错了int f[7][7]= {1,1,0,0,0,1,1,              1,1,0,0,0,1,1,              1,1,1,1,0,1,1,              1,1,1,1,0,1,1,              0,0,0,0,0,2,3,              1,1,1,1,3,1,1,              0,0,0,0,0,3,2             };int cnum;cin >> cnum;getline(cin,s);while(cnum--) {//while(getline(cin,s)){getline(cin,s);int len = s.length();//在输入字符串的后面添加一个等号,目的是和符号栈稍微匹配一下s[len] = '=';++len;stack<int> opf;stack<int> opd;opf.push(6);//先将等号入栈int ind = 0;while(ind < len) {int si = certify(s[ind]);//确定字符if(si == 8) {int tmp1 = gdata(s[ind]);if(ind>0 && certify(s[ind-1])==8) {int tmp2 = opd.top()*10+tmp1;opd.pop();opd.push(tmp2);} else opd.push(tmp1);++ind;} else if (si == 7) ++ind; //空格不做任何处理else {switch(f[opf.top()][si]) {case 0:opf.push(si);++ind;break;case 1: {int b = opd.top();opd.pop();int a = opd.top();opd.pop();int c = opf.top();opf.pop();opd.push(calculate(a,b,c));break;}case 2:opf.pop();++ind;break;case 3:return 0;}}}cout << opd.top()<<endl;}return 0;}