表达式求值:
一、中缀表达式转为后缀表达式:从头到尾读取中缀表达式的每个对象
- 运算数:直接输出
- 左括号:压栈(左括号在栈中的优先级最低)
- 右括号:将栈顶的运算符弹出并输出直至遇到左括号(出栈,不输出)
- 运算符:若优先级大于栈顶运算符时,则把它压栈;
若优先级小于等于栈顶运算符时,将栈顶运算符弹出并输出;再比较新的栈顶运算符,直到该运算符大于栈顶运算符优先级为止,然后将该运算符压栈; - 若各对象处理完毕,则把堆栈中存留的运算符一并输出。
二、后缀表达式求值:从左到右读入后缀表达式的各项。
- 运算数:入栈。
- 运算符:从堆栈中弹出适当数量的运算数,计算出结果并入栈。
- 栈顶元素为表达式的结果值。
例子:
题目:http://118.190.20.162/view.page?gpid=T88
100分解答:
#include<bits/stdc++.h>
using namespace std;
map<char,int>mp;
int main()
{
mp['+']=0;mp['-']=0;mp['x']=1;mp['/']=1;
int n;
string s;
cin>>n;
string postfix="";
stack<char>st;
stack<int>ts;
int a,b;
for(int i=0;i<n;i++)
{
cin>>s;
postfix="";
while(!st.empty())
st.pop();
for(int j=0;j<7;j++)
{
if(s[j]<='9'&&s[j]>='0')
{
postfix+=s[j];
}
else
{
while(!st.empty()&&mp[s[j]]<=mp[st.top()])
{
postfix+=st.top();
st.pop();
}
st.push(s[j]);
}
}
while(!st.empty())
{
postfix+=st.top();
st.pop();
}
//cout<<postfix<<endl;
while(!ts.empty())
ts.pop();
for(int j=0;j<7;j++)
{
if(postfix[j]<='9'&&postfix[j]>'0')
{
ts.push(postfix[j]-'0');
}
else
{
b=ts.top();
ts.pop();
a=ts.top();
ts.pop();
if(postfix[j]=='x')
ts.push(a*b);
else if(postfix[j]=='/')
ts.push(a/b);
else if(postfix[j]=='+')
ts.push(a+b);
else if(postfix[j]=='-')
ts.push(a-b);
}
}
//cout<<ts.top()<<endl;
if(ts.top()==24)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}