NYOJ-1272 表达式求值

时间限制: 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%10;
a/=10;
}
while(b>0)
{
bb += b%10;
b/=10;
}
aa=aa>bb?aa:bb;
dsta.push(aa);
break;
}
osta.pop();
}
osta.pop();
}
}
printf("%d\n",dsta.top());
dsta.pop();
}
return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值