1923: 表达式求值
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 20 Solved: 5
SubmitStatusWeb Board
Description
假设表达式定义为:
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。
请你编程,对给定的表达式,输出其值。
Input
第一行: T 表示要计算的表达式个数 (1≤T≤101≤T≤10)
接下来有 T 行, 每行是一个字符串,表示待求的表达式,长度<=1000
Output
对于每个表达式,输出一行,表示对应表达式的值。
Sample Input
3
12+2*3
12*(2+3)
12*(2+3)+Smax(333,220+280)
Sample Output
18
60
69
HINT
Source
河南省第九届大学生程序设计竞赛
s1 存储 字符,s2 存储 表达式,遇到 ”+“ 便求值
AC代码:
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long LL;
char s[1010];
stack <char> s1;
stack <int> s2;
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%s",s + 1);
int nl = strlen(s + 1);
s[0] = '(',s[++nl] = ')';
for(int i = 0 ; i <= nl; i++){
if(s[i] =='(') s1.push('(');
else if(s[i] == 'S') s1.push('('),i += 3;
else if(s[i] >= '0' && s[i] <= '9'){
LL pl = 0;while(s[i] >= '0' && s[i] <= '9') pl = pl * 10 + s[i++] - '0';
i--,s2.push(pl);
}
else if(s[i] == '+'){ // 可求出存储的表达式值
while(s1.top() != '(' && s1.top() != ','){
int a = s2.top();s2.pop();
int b = s2.top();s2.pop();
if(s1.top() == '+') s2.push(a + b); else s2.push(a * b);
s1.pop();
}
s1.push('+');
}
else if(s[i] == '*') s1.push('*');
else if(s[i] == ')' || s[i] == ','){
while(s1.top() != '('){
int a = s2.top();s2.pop();
int b = s2.top();s2.pop();
if(s1.top() == '+') s2.push(a + b);
else if(s1.top() == '*') s2.push(a * b);
else{
LL n1 = 0,n2 = 0;
while(a) n1 += a % 10,a /= 10; while(b) n2 += b % 10,b /= 10;
s2.push(max(n1,n2));
}
s1.pop();
}
s1.pop(); // 左括号可去除
if(s[i] == ',') s1.push(',');
}
}
printf("%d\n",s2.top());s2.pop();
}
return 0;
}