P1175-表达式的转换
表达式的转换
题目描述
平常我们书写的表达式称为中缀表达式,因为它将运算符放在两个操作数中间,许多情况下为了确定运算顺序,括号是不可少的,而中缀表达式就不必用括号了。
后缀标记法:书写表达式时采用运算紧跟在两个操作数之后,从而实现了无括号处理和优先级处理,使计算机的处理规则简化为:从左到右顺序完成计算,并用结果取而代之。
例如:8-(3+2*6)/5+4
可以写为:8 3 2 6*+5/-4+
其计算步骤为:
8 3 2 6 * + 5 / – 4 +
8 3 12 + 5 / – 4 +
8 15 5 / – 4 +
8 3 – 4 +
5 4 +
9
编写一个程序,完成这个转换,要求输出的每一个数据间都留一个空格。
输入格式
就一行,是一个中缀表达式。输入的符号中只有这些基本符号0123456789+-*/^()
,并且不会出现形如2*-3
的格式。
表达式中的基本数字也都是一位的,不会出现形如12
形式的数字。
所输入的字符串不要判错。
输出格式
若干个后缀表达式,第I+1
行比第I
行少一个运算符和一个操作数,最后一行只有一个数字,表示运算结果。
`
样例 #1
样例输入 #1
8-(3+2*6)/5+4
样例输出 #1
8 3 2 6 * + 5 / - 4 +
8 3 12 + 5 / - 4 +
8 15 5 / - 4 +
8 3 - 4 +
5 4 +
9
提示
运算的结果可能为负数,/
以整除运算。并且中间每一步都不会超过
Solution
AC Code
#include <iostream>
#include <stack>
#include <cmath>
#include <string>
#include <list>
#include <cctype>
using namespace std;
int priority_judge(const char& ch) {
switch(ch) {
case '(': case ')': return 0;
case '+': case '-': return 1;
case '*': case '/': return 2;
case '^': return 3;
}
return -1;
}
string toSuffix(const string& str) {
stack<char> s; string tmp = "";
for(int i = 0; i < str.length(); ++i) {
if(isdigit(str[i])) tmp += str[i];
else if(str[i] == '(') s.push(str[i]);
else if(str[i] == ')') {
while(s.top() != '(') tmp += s.top(), s.pop();
s.pop();
} else {
while(!s.empty() && priority_judge(s.top()) >= priority_judge(str[i]))
tmp += s.top(), s.pop();
s.push(str[i]);
}
}
while(!s.empty()) tmp += s.top(), s.pop();
return tmp;
}
inline int calcNum(const int& ident, const int& num1, const int& num2) {
switch(ident) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return num1 * num2;
case '/': return num1 / num2;
case '^': return (int) pow (num1, num2);
}
return -1;
}
void printSuf(string tmp) {
for(int i = 0; i < tmp.length(); ++i)
cout << tmp[i] << ' ';
cout << endl;
}
void calcPrint(const string& str) {
list<int> ls;
printSuf(str);
for(int i = 0; i < str.length(); ++i) {
if(isdigit(str[i])) ls.push_back(str[i] - '0');
else {
int num1 = ls.back(); ls.pop_back();
int num2 = ls.back(); ls.pop_back();
ls.push_back(calcNum(str[i], num2, num1));
for(auto it = ls.begin(); it != ls.end(); ++it)
cout << *it << ' ';
for(int j = i + 1; j < str.length(); ++j)
cout << str[j] << ' ';
cout << endl;
}
}
}
int main() {
string str;
cin >> str;
calcPrint(toSuffix(str));
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?