题解————正误问题

· · 题解

正如标签所言,这道题是一道栈的题,我们可以使用STL中的stack来解决

我们可以考虑开两个栈,然后根据题上not->and->or的优先级顺序入q栈。

if(a=="or")
{
while(!q.empty()) 
  begin_todo();
q.push(1); //优先级为1
}
else 
if(a=="and")
{
while(!q.empty()&&q.top()>=2) 
  begin_todo();//优先级为2
q.push(2);
}     
else 
if(a=="not")
q.push(3);//优先级为3

在上文出现了一个begin_todo函数,这个函数主要有两个功能:判错与计算。在这个函数中如果有错就会直接输出“error”并结束运行,否则就将数据进行或(or)非(!)与(and)运算并再次将运算结果入栈。下面上代码

inline void begin_todo()
{
    int head=q.top();
    q.pop();
    int x,y;
    if(head==1)
    if(s.size()<2)
    cout<<"error",exit(0);
    else
    x=s.top(),s.pop(),y=s.top(),s.pop(),s.push(x or y);
    if(head==2)
    if(s.size()<2)
    cout<<"error",exit(0);
    else
    x=s.top(),s.pop(),y=s.top(),s.pop(),s.push(x and y);
    if(head==3)
    if(s.empty())
    cout<<"error",exit(0);
    else
    x=s.top(),s.pop(),s.push(!x);
    return ;
}

然后将“true”和“false”入到s栈中

else 
if(a=="not")
q.push(3);
else 
if(a=="true") 
s.push(1);
else 
if(a=="false")
s.push(0);

最后将q栈中剩余元素清空并特判三种情况

while(!q.empty())
begin_todo();
int tops=s.top();
s.pop();
if(s.empty()&&tops==1)
cout<<"true";
else
if(s.empty()&&tops!=1)
cout<<"false";
else
cout<<"error";

这样的话这道题就结束了,有需要的可以点我拿完整代码

最后祝大家AC愉快!