题目链接: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;
}
}