题解 P1575 【正误问题】

· · 题解

这题我用了很长时间。就是把中缀转后缀,有符号就看看有没有足够的true和false给你运算。有的话就把结果压入栈,没有就输出error。

附上代码:

#include<iostream>
#include<stack>
using namespace std;
int d[10005],f[10005],a1,a2;
stack<int>ys;//ys=运算
stack<int>ysf;//ysf=运算符
int main(){
    string a,p="";
    int i,q=0,w=0;
    getline(cin,a);
    a+=' ';
    for(i=0;i<a.size();i++){
        if(a[i]==' '){
            //cout<<p<<endl;
            if(p!=""){//字符串运算太麻烦,所以我转成数字
                if(p=="true")d[++q]=1;
                if(p=="false")d[++q]=0;
                if(p=="or")d[++q]=2;
                if(p=="and")d[++q]=3;
                if(p=="not")d[++q]=4;
                p="";
            }
        }
        else p+=a[i];
    }
    for(i=1;i<=q;i++){
        if(d[i]>1){
            for(;;){
                if(ysf.size()>0&&ysf.top()>=d[i]&&d[i]<4){
                    f[++w]=ysf.top();
                    ysf.pop();
                }
                else{
                    ysf.push(d[i]);
                    break;
                }
            }
        }
        else f[++w]=d[i];
    }
    for(;;){
        if(ysf.size()==0)break;
        f[++w]=ysf.top();
        ysf.pop();
    }
    for(i=1;i<=w;i++){
        if(f[i]<=1){
            ys.push(f[i]);
        }
        else{
            if(f[i]==2){
                if(ys.size()<2){
                    cout<<"error";
                    return 0;
                }
                a1=ys.top();
                ys.pop();
                a2=ys.top();
                ys.pop();
                if(a1==1||a2==1)ys.push(1);
                else ys.push(0);
            }
            if(f[i]==3){
                if(ys.size()<2){
                    cout<<"error";
                    return 0;
                }
                a1=ys.top();
                ys.pop();
                a2=ys.top();
                ys.pop();
                if(a1==1&&a2==1)ys.push(1);
                else ys.push(0);
            }
            if(f[i]==4){
                if(ys.size()<1){
                    cout<<"error";
                    return 0;
                }
                a1=ys.top();
                ys.pop();
                if(a1==1)ys.push(0);
                else ys.push(1);
            }
        }
    }
    if(ys.size()!=1){//没有结果的情况
        cout<<"error";
        return 0;
    }
    if(ys.top()==1)cout<<"true";
    else cout<<"false";
}