题目链接:http://hihocoder.com/contest/hiho169/problem/1
题目解答:
输入表达式之后,转化成后缀表达式(逆波兰表达式)
中缀表达式转后缀表达式的方法:
1.遇到操作数:直接输出(添加到后缀表达式中)
2.栈为空时,遇到运算符,直接入栈
3.遇到左括号:将其入栈
4.遇到右括号:执行出栈操作,并将出栈的元素输出,直到弹出栈的是左括号,左括号不输出。
5.遇到其他运算符:加减乘除:弹出所有优先级大于或者等于该运算符的栈顶元素,然后将该运算符入栈
6.最终将栈中的元素依次出栈,输出。
例如
a+b*c+(d*e+f)g —-> abc+de*f+g*+
遇到a:直接输出:
后缀表达式:a
堆栈:空
遇到+:堆栈:空,所以+入栈
后缀表达式:a
堆栈:+
遇到b: 直接输出
后缀表达式:ab
堆栈:+
遇到:堆栈非空,但是+的优先级不高于,所以*入栈
后缀表达式: ab
堆栈:*+
遇到c:直接输出
后缀表达式:abc
堆栈:*+
遇到+:堆栈非空,堆栈中的*优先级大于+,输出并出栈,堆栈中的+优先级等于+,输出并出栈,然后再将该运算符(+)入栈
后缀表达式:abc*+
堆栈:+
遇到(:直接入栈
后缀表达式:abc*+
堆栈:(+
遇到d:输出
后缀表达式:abc*+d
堆栈:(+
遇到:堆栈非空,堆栈中的(优先级小于,所以不出栈
后缀表达式:abc*+d
堆栈:*(+
遇到e:输出
后缀表达式:abc*+de
堆栈:*(+
遇到+:由于的优先级大于+,输出并出栈,但是(的优先级低于+,所以将出栈,+入栈
后缀表达式:abc*+de*
堆栈:+(+
遇到f:输出
后缀表达式:abc*+de*f
堆栈:+(+
遇到):执行出栈并输出元素,直到弹出左括号,所括号不输出
后缀表达式:abc*+de*f+
堆栈:+
遇到*:堆栈为空,入栈
后缀表达式: abc*+de*f+
堆栈:*+
遇到g:输出
后缀表达式:abc*+de*f+g
堆栈:*+
遇到中缀表达式结束:弹出所有的运算符并输出
后缀表达式:abc*+de*f+g*+
堆栈:空
后缀表达式算法
设置一个栈,开始时,栈为空,然后从左到右扫描后缀表达式,若遇操作数,则进栈;若遇运算符,则从栈中退出两个元素,先退出的放到运算符的右边,后退出的 放到运算符左边,运算后的结果再进栈,直到后缀表达式扫描完毕。此时,栈中仅有一个元素,即为运算的结果。
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<queue>
#include<map>
#include<stack>
#include<vector>
#include<list>
#include<deque>
using namespace std;
typedef long long ll;
const int maxn = + ;
const double eps = ;
const int INF = << ;
int T, n, m;
int q[];
map<char, int>Map;
void init()
{
Map['+'] = ;
Map['-'] = ;
Map['*'] = ;
Map['/'] = ;
Map['('] = ;
}
void solve (string s, string& ans, int & sum)
{
ans = "";
int num = , tot = ;
for(int i = ; i < s.size(); i++)
{
if(isdigit(s[i]))num++;
else if(num)q[tot++] = num, num = ;
}
if(num)q[tot++] = num;
stack<char>sign;
char c;
for(int i = ; i < s.size(); i++)
{
if(isdigit(s[i]))ans += s[i];
else
{
if(sign.empty() || s[i] == '(')sign.push(s[i]);
else
{
if(s[i] == ')')
{
while()
{
c = sign.top();
sign.pop();
if(c == '(')break;
ans += c;
}
}
else
{
while()
{
if(sign.empty())
{
sign.push(s[i]);
break;
}
c = sign.top();
if(Map[c] < Map[s[i]])
{
sign.push(s[i]);
break;
}
else
{
ans += c;
sign.pop();
}
//cout<<"c::"<<c<<endl;
}
}
}
}
}
while(!sign.empty())ans += sign.top(),sign.pop();
// cout<<ans<<endl;
stack<int>took; // cout<<ans<<" "<<ans2<<endl;
tot = num = ;
int a, b;
for(int i = ; i < ans.size(); i++)
{
if(isdigit(ans[i]))
{
for(int j = i; j < i + q[tot]; j++)
{
num = num * + ans[j] - '0';
}
i = i + q[tot++] - ;
took.push(num);
//cout<<num<<endl;
num = ;
}
else
{
a = took.top();
//cout<<"a"<<a<<endl;
took.pop();
b = took.top();
//cout<<"b"<<b<<endl;
took.pop();
if(ans[i] == '*')took.push(a * b);
if(ans[i] == '+')took.push(a + b);
if(ans[i] == '-')took.push(b - a);
if(ans[i] == '/')took.push(b / a);
}
}
sum = took.top();
}
int main()
{
string s, ans;
int num;
init();
while(cin >> s)
{
solve(s, ans, num);
cout<<num<<endl;
}
return ;
}