NYOJ-1272 表达式求值

    xiaoxiao2021-04-16  27

    时间限制: 1000 ms  |  内存限制: 65535 KB 难度: 3 描述 假设表达式定义为: 1. 一个十进制的正整数 X 是一个表达式。 2. 如果 X 和 Y 是 表达式,则 X+Y, X*Y 也是表达式; *优先级高于+. 3. 如果 X 和 Y 是 表达式,则 函数 Smax(X,Y)也是表达式,其值为:先分别求出 X ,Y 值的各位数字之和,再从中选最大数。 4.如果 X 是 表达式,则 (X)也是表达式。 例如: 表达式 12*(2+3)+Smax(333,220+280) 的值为 69。 请你编程,对给定的表达式,输出其值。   输入 【标准输入】 第一行: T 表示要计算的表达式个数 (1≤ T ≤ 10) 接下来有 T 行, 每行是一个字符串,表示待求的表达式,长度<=1000 输出 【标准输出】 对于每个表达式,输出一行,表示对应表达式的值。 样例输入 3 12+2*3 12*(2+3) 12*(2+3)+Smax(333,220+280) 样例输出 18 60 69

    #include <stdio.h>#include <string.h>#include <stack>#include <ctype.h>char s[1005];std:: stack <int> dsta;std:: stack <char> osta;int main(){ int n; scanf("%d",&n); s[0]='('; while(n--) { scanf("%s",s+1); int len=strlen(s); s[len]=')'; for(int i=0;i<len+1;i++) { if(isdigit(s[i])) { int a=0; while(isdigit(s[i])) a = a*10+(s[i++]-'0'); i--; dsta.push(a); } else if(s[i]=='S') i += 3; else if(s[i]=='(') osta.push('('); else if(s[i]=='+'||s[i]=='-') { int a,b; while(osta.top()!='('&&osta.top()!=',') { a=dsta.top();dsta.pop(); b=dsta.top();dsta.pop(); switch(osta.top()) { case '+': dsta.push(b+a);break; case '-': dsta.push(b-a);break; case '*': dsta.push(b*a);break; } osta.pop(); } osta.push(s[i]); } else if(s[i]=='*') { int a,b; switch(osta.top()) { case '*': a=dsta.top();dsta.pop(); b=dsta.top();dsta.pop(); dsta.push(b*a); osta.pop();break; default: osta.push('*');break; } } else if(s[i]==',') { int a,b; while(osta.top()!='(') { a=dsta.top();dsta.pop(); b=dsta.top();dsta.pop(); switch(osta.top()) { case '*': dsta.push(b*a); break; case '+': dsta.push(b+a); break; case '-': dsta.push(b-a); break; } osta.pop(); } osta.push(','); } else if(s[i]==')') { int a,b,aa=0,bb=0; while(osta.top()!='(') { a=dsta.top();dsta.pop(); b=dsta.top();dsta.pop(); switch(osta.top()) { case '+': dsta.push(b+a);break; case '-': dsta.push(b-a);break; case '*': dsta.push(b*a);break; case ',': while(a>0) { aa += a; a/=10; } while(b>0) { bb += b; b/=10; } aa=aa>bb?aa:bb; dsta.push(aa); break; } osta.pop(); } osta.pop(); } } printf("%d\n",dsta.top()); dsta.pop(); } return 0;}

    转载请注明原文地址: https://ju.6miu.com/read-672534.html

    最新回复(0)