题解 P1575 【正误问题】
根据解中缀表达式的思路去做,再加个栈下溢判错就行了
中缀表达式的思路:遇到一个符号,先把前面运算优先级不比它小的运算解决出栈,最后再一起出栈
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
string str;
int s[256],l1,l2;
bool f[256];
void pop() //出栈
{
switch(s[l1])
{
case 1:if(l2<2) {puts("error");exit(0);}f[l2-1]=f[l2-1]||f[l2];--l2;break;
case 2:if(l2<2) {puts("error");exit(0);}f[l2-1]=f[l2-1]&&f[l2];--l2;break;
case 3:if(!l2) {puts("error");exit(0);}f[l2]=!f[l2];break;
}
--l1;
}
int main()
{
for(;cin>>str;)
if(str=="and") {for(;l1&&(s[l1]>=2);) pop();s[++l1]=2;}
else if(str=="or") {for(;l1;pop());s[++l1]=1;}
else if(str=="not") s[++l1]=3;
else if(str=="true") f[++l2]=true;
else if(str=="false") f[++l2]=false;
for(;l1;pop());
if(l2==1) puts(f[1]?"true":"false");
else puts("error");
return 0;
}