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 ≤ 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
河南省第九届大学生程序设计竞赛
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
stack <int> sta;// 储存数据
stack <char> st;//储存字符
char pa[1011];
int main()
{
int T,i,pl;
scanf("%d",&T);
while(T--)
{
scanf("%s",&pa[1]);
pl = strlen(&pa[1]);
pa[0] = '('; pa[++pl] = ')';//在表达式两端添加一对小括号
for(i = 0; i <= pl; i++)
{
if(pa[i] == '(')
st.push(pa[i]);
else if(pa[i] == 'S')
{
st.push('(');
i += 3;
}
else if(pa[i] >= '0' && pa[i] <= '9')
{
int vl=0;
while(pa[i] >= '0' && pa[i] <= '9')
vl = vl * 10 + (pa[i++] - '0');
i--;
sta.push(vl);
}
else if(pa[i] == '+')
{
while(st.top() != '(' && st.top() != ',')
{
int a = sta.top(); sta.pop();
int b = sta.top(); sta.pop();
int ans;
switch(st.top())
{
case '+' : ans = a + b;break;
case '*' : ans = a * b;break;
}
sta.push(ans);
st.pop();
}
st.push(pa[i]);
}
else if(pa[i] == '*')
{
if(st.top() == '*')
{
int a = sta.top(); sta.pop();
int b = sta.top(); sta.pop();
sta.push(a * b);
st.pop();
}
st.push(pa[i]);
}
else if(pa[i] == ')' || pa[i] == ',')//遇到逗号及时求值
{//当与道逗号时及时求出,Smax前半部分表达式的值
while(st.top() != '(')
{
int a = sta.top(); sta.pop();
int b = sta.top(); sta.pop();
int ans,ans1 = 0, ans2 = 0;
switch(st.top())
{
case '+' : ans = a + b;break;
case '*' : ans = a * b;break;
case ',' :
{
while(a)
{
ans1 += a % 10;
a /= 10;
}
while(b)
{
ans2 += b % 10;
b /= 10;
}
ans = max(ans1,ans2);
break;
}
}
sta.push(ans);
st.pop();
}
st.pop();
if(pa[i] == ',') //求完值以后,把逗号压入栈内,以便求出Smax后半部分表达式的值
st.push(pa[i]);
}
}
printf("%d\n",sta.top());
sta.pop();
}
return 0;
}