您的位置:首页 > 理论基础 > 数据结构算法

nyoj 1272 表达式求值(中缀式转后缀式)

2016-09-29 20:42 363 查看


表达式求值

时间限制: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<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
using namespace std;

const int maxn = 1005;
int n; //表示串的长度
char str[maxn];
stack<int> s1;
stack<char> s2;

int getNum(int L,int R)
{
int num = 0;
for(int i = L; i <= R; i++)
num = num * 10 + str[i] - '0';
return num;
}

int Calc(char op,int a,int b)
{
if(op == '+') return a + b;
else if(op == '*') return a * b;
else {
int tmpa = 0, tmpb = 0;
while(a > 0) {
tmpa += a % 10;
a /= 10;
}
while(b > 0) {
tmpb += b % 10;
b /= 10;
}
return max(tmpa,tmpb);
}
}

int process() //将中缀式转化为后缀式
{
int a,b;
char c;
while(!s1.empty()) s1.pop();
while(!s2.empty()) s2.pop();
s2.push('#');
for(int i = 0; i < n; i++) {
if(str[i] == 'S' || str[i] == 'm' || str[i] == 'a' || str[i] == 'x') continue;
if(str[i] == '(')
s2.push(str[i]);
else if(str[i] == ')') {
c = s2.top();
while(c != '(') {
a = s1.top(); s1.pop();
b = s1.top(); s1.pop();
s1.push(Calc(c,a,b));
s2.pop();
c = s2.top();
}
s2.pop();
}
else if(str[i] >= '0' && str[i] <= '9') {
int j = i;
while(str[j] >= '0' && str[j] <= '9' && j < n) j++;
j--;
s1.push(getNum(i,j));
i = j;
}
else if(str[i] == '+') {
c = s2.top();
while(c == '*' || c == '+') {
a = s1.top(); s1.pop();
b = s1.top(); s1.pop();
s1.push(Calc(c,a,b));
s2.pop();
c = s2.top();
}
s2.push('+');
}
else if(str[i] == '*') {
c = s2.top();
while(c == '*') {
a = s1.top(); s1.pop();
b = s1.top(); s1.pop();
s1.push(Calc(c,a,b));
s2.pop();
c = s2.top();
}
s2.push('*');
}
else if(str[i] == ',') s2.push(str[i]);
}
while(s2.top() != '#') {
c = s2.top();
s2.pop();
a = s1.top(); s1.pop();
b = s1.top(); s1.pop();

s1.push(Calc(c,a,b));
if(c == '+')
{
int p = 1;
}
}
return s1.top();
}

int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",str);
n = strlen(str);
printf("%d\n",process());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构