如注释所见,前面定义了int pp,qq,rr,ss,tt后面又来一遍,真的很惨很惨,bug到顶了。。。
题目大意:大致题意:
输入由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
A --> or: x || y
N --> not : !x
C --> implies : (!x)||y
E --> equals : x==y
问这个逻辑表达式是否为永真式。
PS:输入格式保证是合法的
解题思路:
p, q, r, s, t不同的取值组合共32种情况,枚举不同取值组合代入逻辑表达式WFF进行计算。
如果对于所有的取值组合,WFF值都为 true, 则结果为 tautology,否则为 not。
WFF的计算方法:
从字符串WFF的末尾开始依次向前读取字符。
构造一个栈stack,当遇到逻辑变量 p, q, r, s ,t 则将其当前的值压栈;
遇到 N 则取栈顶元素进行非运算,运算结果的值压栈;
遇到K, A, C, E则从栈顶中弹出两个元素进行相应的运算,将结果的值压栈。
由于输入是合法的,当字符串WFF扫描结束时,栈stack中只剩一个值,该值就是逻辑表达式WFF的值。
#include <iostream>
using namespace std;
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <string.h>
#include <stack>
int pp,qq,rr,ss,tt;
stack<int> s;
bool isvarieble(char ch);
void operatorx(char op);
int main()
{
char WFF[110];
while(cin>>WFF && WFF[0]!='0')
{
int len=strlen(WFF);
bool flag=true;
for(pp=0;pp<=1;pp++)//不能为int pp=0;pp<=1;pp++,BUG很久!!!~ ~真不容易
{
for(qq=0;qq<=1;qq++)
{
for(rr=0;rr<=1;rr++)
{
for(ss=0;ss<=1;ss++)
{
for(tt=0;tt<=1;tt++)
{
for(int pw=len-1;pw>=0;pw--)
{
if(!isvarieble(WFF[pw]))
{
operatorx(WFF[pw]);
}
}
int result=s.top();
s.pop();
if(!result)
{
flag=false;
break;
}
}
if(!flag)
break;
}
if(!flag)
break;
}
if(!flag)
break;
}
if(!flag)
break;
}
if(flag)
printf("tautology\n");
else
printf("not\n");
}
return 0;
}
bool isvarieble(char ch)
{
switch(ch)
{
case 'p':s.push(pp);return true;
case 'q':s.push(qq);return true;
case 'r':s.push(rr);return true;
case 's':s.push(ss);return true;
case 't':s.push(tt);return true;
}
return false;
}
void operatorx(char op)
{
switch(op)
{
case 'K':
{
int tmp1=s.top();
s.pop();
int tmp2=s.top();
s.pop();
s.push(tmp1&&tmp2);
break;
}
case 'A':
{
int tmp1=s.top();
s.pop();
int tmp2=s.top();
s.pop();
s.push(tmp1||tmp2);
break;
}
case 'C':
{
int tmp1=s.top();
s.pop();
int tmp2=s.top();
s.pop();
s.push((!tmp1)||tmp2);
break;
}
case 'E':
{
int tmp1=s.top();
s.pop();
int tmp2=s.top();
s.pop();
s.push(tmp1==tmp2);
break;
}
case 'N':
{
int tmp1=s.top();
s.pop();
s.push(!tmp1);
break;
}
}
return;
}