题解 P1575 【正误问题】
这道题目很多人可能看都要看傻了,所以我们先来解释一下题意,类似c++的判断,
or=||
not=!
and=&&
如果最终表达式的值为真,输出true,假为false,不是表达式就直接输出error就行啦。
这道题用栈的思路可以很好解出,而且还莫得“(” 和 “)”,岂不美哉?
在写代码之前,一定要注意一点:empty()要勤用哦
不说了,上代码
#include<bits/stdc++.h>//万能头
using namespace std;
string st;
stack<int>s1;
stack<bool>a;//其实int也可以,但是这样好看
void xxx()//函数名似乎有点丑
{
if(s1.top()==3)
{
if(a.empty())
{
cout<<"error";
exit(0);
}
bool flag=a.top();
flag=!flag;
a.pop();
a.push(flag);
}
if(s1.top()==2)
{
if(a.size()<2)
{
cout<<"error";
exit(0);//不要用return(过来人的忠告)
}
bool flag=a.top();
a.pop();
flag=flag and a.top();
a.pop();
a.push(flag);
}
if(s1.top()==1)
{
if(a.size()<2)
{
cout<<"error";
exit(0);
}
bool flag=a.top();
a.pop();
flag=flag or a.top();
a.pop();
a.push(flag);
}
s1.pop();
}
int main()
{
while(cin>>st)//string就是舒服
{
if(st=="not")
{
s1.push(3);
}
else if(st=="and")
{
while(!s1.empty()&&(s1.top()>=2))xxx();
s1.push(2);
}
else if(st=="or")
{
while(!s1.empty())xxx();
s1.push(1);
}
else if(st=="true")a.push(1);
else if(st=="false")a.push(0);
}
while(!s1.empty())xxx();
if (a.size()==1)
{
if(a.top())
{
cout<<"true";
}
else
{
cout<<"false";
}
}
else cout<<"error";
return 0;//好习惯要养成
}