思路
建立一个用于存数的栈,逐一扫描后缀表达式中的元素。
①如果遇到一个数字,将改数字入栈。
②遇到一个运算符,如果该运算符是一个二元运算符,如&,|等,则弹出栈顶的两个数字运算。如果该运算符是一元运算符,如!,则弹出栈顶的一个数字运算。将运算后的结果再次入栈。
扫描完成后,栈中恰好剩下一个数字,就是该后缀表达式的值。
code
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+5;
map<char, bool> mp;
stack<bool> st;
int n;
string s;
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
char c;
cin >> c;
getchar();
if(c == 'T')
mp[char(i + 'A' - 1)] = true;
else
mp[char(i + 'A' - 1)] = false;
}
getline(cin, s);
int len = s.size();
for(int i = 0; i < len; i++)
{
if(s[i] == ' ')
continue;
else if(s[i] >= 'A' && s[i] <= 'Z')
{
st.push(mp[s[i]]);
/*cout << st.top() << endl;
system("pause");*/
}
else
{
if(s[i] == '*')
{
if(st.size() >= 2)
{
bool a = st.top();
st.pop();
bool b = st.top();
st.pop();
bool c = (a && b);
st.push(c);
}
}
else if(s[i] == '+')
{
if(st.size() >= 2)
{
bool a = st.top();
st.pop();
bool b = st.top();
st.pop();
bool c = (a || b);
st.push(c);
}
}
else
{
if(st.size())
{
bool a = st.top();
st.pop();
bool b = (!a);
st.push(b);
}
}
}
}
if(st.top() == 0)
cout << 'F' << endl;
if(st.top() == 1)
cout << 'T' << endl;
return 0;
}