8.1 poj 3295 Tautology

题目链接:http://poj.org/problem?id=3295

算法:构造法

题意:输入由p,q,r,s,t,K,A,N,C,E共10个字母组成的逻辑表达式,其中p,q,r,s,t的值为1(true)或0(false),即逻辑变量;K,A,N,C,E为逻辑运算符。

K--> and: x & y 或者x && y

A--> or: x | y或者x | | y

N--> not: (~x)&1 或者(!x )

C--> implies: (~x) | y或者(!x ) | | y

E--> equals: x == y

问这个逻辑表达式是否为永真式。

思路:对于每个逻辑变量的每个取值,都依次枚举,判断对于每一种逻辑变量的取值情况表达式是否为真

#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<stack>
using namespace std;
char str[105];
int p,q,r,s,t,len;
int result(){
    stack<int>g;
    int n1,n2;
    for(int i=len-1;i>=0;i--){
       switch(str[i]){
        case 'p':
            g.push(p);
        break;
        case 'q':
            g.push(q);
        break;
        case 's':
            g.push(s);
        break;
        case 'r':
            g.push(r);
        break;
        case 't':
            g.push(t);
        break;
        case 'K':
            n1=g.top();
            g.pop();
            n2=g.top();
            g.pop();
            if(n1&&n2)
                g.push(1);
            else g.push(0);
        break;
        case 'A':
            n1=g.top();
            g.pop();
            n2=g.top();
            g.pop();
            if(n1||n2)
                g.push(1);
            else g.push(0);
        break;
        case 'N':
            n1=g.top();
            g.pop();
            if((!n1))
                g.push(1);
            else g.push(0);
        break;
        case 'C':
            n1=g.top();
            g.pop();
            n2=g.top();
            g.pop();
            if(((!n1))||n2)
                g.push(1);
            else g.push(0);
        break;
        case 'E':
            n1=g.top();
            g.pop();
            n2=g.top();
            g.pop();
            if(n1==n2)
                g.push(1);
            else g.push(0);
        break;
       }
    }
    return g.top();
}
int fun(){
    int flag;
for(p=0;p<2;p++){
             for(q=0;q<2;q++){
                 for(r=0;r<2;r++){
                      for(s=0;s<2;s++){
                          for(t=0;t<2;t++){
                            flag=result();
                            if(flag==0) return 0;
        }
        }
        }
        }
        }
        return 1;
}
int main ()
{
    int flag;
     while(cin>>str){
        if(strcmp(str,"0")==0) break;
        len=strlen(str);
        flag=fun();
        if(flag==0) cout<<"not"<<endl;
        else cout<<"tautology"<<endl;
     }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值