【热身训练赛第三场】 A Circuit Math
后缀表达式+简单数字电路
输入电路元件(字母)的状态(T或F)及其连接方式(*表示与,+表示或,-表示非),输出最后的运算结果。
对输入从前往后处理,若遇到字母,则将其值(True或False)存入栈中;若遇到运算符,则取出栈顶的一个(非)或两个(与、或)元素进行运算,并将运算得到的结果存入栈中。最终栈中剩下的那个元素即为要求的答案。
样例输入:
4
T F T F
A B * C D + - +
样例输出:
F
AC代码:
#include <iostream>
#include <cstdio>
#include <stack>
#include <sstream>
using namespace std;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n;
char c;
bool a[26];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>c;
if(c=='T')
a[i]=true;
else
a[i]=false;
}
cin.ignore();
stringstream ss;
string s;
getline(cin,s);
ss<<s;
stack<bool> sta;
while(ss>>c)
{
if(c>='A'&&c<='Z')
sta.push(a[c-'A']);
if(c=='*')
{
bool a=sta.top();
sta.pop();
bool b=sta.top();
sta.pop();
bool t=a&&b;
sta.push(t);
}
if(c=='+')
{
bool a=sta.top();
sta.pop();
bool b=sta.top();
sta.pop();
bool t=a||b;
sta.push(t);
}
if(c=='-')
{
bool a=sta.top();
sta.pop();
bool t=!a;
sta.push(t);
}
}
char t=sta.top();
if(t==true)
printf("T");
else
printf("F");
return 0;
}