算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、/以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
- #include <bits/stdc++.h>
- using namespace std;
- #define int long long
- #define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
- typedef pair<int,int> PII;
- const int N=2e6+10;
- string s,p;
- stack <char> q;
- vector <string> k;
- int str[N];
- signed main()
- {
- ios;
- str['+']=str['-']=1;
- str['*']=str['/']=2;
- cin>>s;
- for (int i=0;i<s.size();i++)
- {
- if (s[i]>='0'&&s[i]<='9'||((i==0||s[i-1]=='(')&&(s[i]=='+'||s[i]=='-')))
- {
- p.clear();
- if (s[i]!='+') p +=s[i];
- while (s[i+1]>='0'&&s[i+1]<='9'||s[i+1]=='.')
- {
- p +=s[i+1];
- i++;
- }
- k.push_back(p);
- }
- else if (s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
- {
- while (q.size()&&str[q.top()]>=str[s[i]])
- {
- p.clear();
- p +=q.top();
- k.push_back(p);
- q.pop();
- }
- q.push(s[i]);
- }
- else if (s[i]=='(') q.push('(');
- else
- {
- while (q.top()!='(')
- {
- p.clear();
- p +=q.top();
- k.push_back(p);
- q.pop();
- }
- q.pop();
- }
- }
- while (q.size())
- {
- p.clear();
- p +=q.top();
- k.push_back(p);
- q.pop();
- }
- for (int i=0;i<k.size();i++)
- {
- cout<<k[i];
- if (i!=k.size()-1) cout<<" ";
- }
- return 0;
- }