您的位置:首页 > 其它

nyist 1272 表达式求值 (河南省第九届省赛) 中缀转后缀

2016-10-05 20:57 537 查看
描述
假设表达式定义为: 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<bits/stdc++.h>
#include<stack>
const int MAX=100;
using namespace std;
char pp[MAX];//存储转换后的后缀表达式
void trans(char str[])//将中缀表达式转换后缀表达式
{
stack<char>ss;
int i,j;
i=0;
j=0;
while(str[i]!='#')
{
if(str[i]=='(')
{
ss.push(str[i]);
}
else if(str[i]==')')
{
while(ss.top()!='(')
{
pp[j++]=ss.top();
ss.pop();
}
ss.pop();
}
else if(str[i]==',')
{
while(ss.top()!='(')
{
pp[j++]=ss.top();
ss.pop();
}
ss.push(str[i]);

}
else if(str[i]=='+'||str[i]=='-')
{
while((!ss.empty())&&(ss.top()!='(')&&(ss.top()!=','))
{
pp[j++]=ss.top();
ss.pop();
}
ss.push(str[i]);
}
else if(str[i]=='*'||str[i]=='/')
{
while((!ss.empty()&&ss.top()=='*')||(!ss.empty()&&ss.top()=='/'))
{
pp[j++]=ss.top();
ss.pop();
}
ss.push(str[i]);
}
else if(str[i]==' '||str[i]=='S'||str[i]=='m'||str[i]=='a'||str[i]=='x')
{
i++;
continue;
}
else
{
while(str[i]>='0'&&str[i]<='9')
{
pp[j++]=str[i];
i++;
}
i--;
pp[j++]='#';
}
i++;
}
while(!ss.empty())
{
pp[j++]=ss.top();
ss.pop();
}
pp[j]='#';
//    for(int k=0; k<=j; k++)//输出转化后的后缀表达式
//    {
//        printf("%c",pp[k]);
//    }
//    printf("\n");
}
void compvalue()//计算后缀表达式的值
{
int d;
stack<int>mm;
int i;
i=0;
while(pp[i]!='#')
{
if(pp[i]=='+')
{
int r=mm.top();
mm.pop();
int l=mm.top();
mm.pop();
int result=l+r;
mm.push(result);
}
else if(pp[i]=='-')
{
int r=mm.top();
mm.pop();
int l=mm.top();
mm.pop();
int result=l-r;
mm.push(result);
}
else if(pp[i]=='*')
{
int r=mm.top();
mm.pop();
int l=mm.top();
mm.pop();
int result=l*r;
mm.push(result);
}
else if(pp[i]=='/')
{
int r=mm.top();
mm.pop();
int l=mm.top();
mm.pop();
int result=l/r;
mm.push(result);
}
else if(pp[i]==',')
{
int r=mm.top();
mm.pop();
int l=mm.top();
mm.pop();
int sum=0,sum1=0;
while(r)
{
sum+=r%10;
r/=10;
}
while(l)
{
sum1+=l%10;
l/=10;
}
int result=max(sum,sum1);
mm.push(result);
}
else
{
d=0;
while(pp[i]>='0'&&pp[i]<='9')
{
d=10*d+pp[i]-'0';
i++;
}
mm.push(d);
}
i++;
}
printf("%d\n",mm.top());
}
int main()
{
int t;
char str[MAX];
scanf("%d",&t);
getchar();
while(t--)
{
gets(str);
int len=strlen(str);
str[len]='#';
trans(str);
compvalue();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: