Description
WFF 'N PROOF is a logic game played with dice. Each die has six faces representing some subset of the possible symbols K, A, N, C, E, p, q, r, s, t. A Well-formed formula (WFF) is any string of these symbols obeying the following rules:
- p, q, r, s, and t are WFFs
- if w is a WFF, Nw is a WFF
- if w and x are WFFs, Kwx, Awx, Cwx, and Ewx are WFFs.
- p, q, r, s, and t are logical variables that may take on the value 0 (false) or 1 (true).
- K, A, N, C, E mean and, or, not, implies, and equals as defined in the truth table below.
|
w x | Kwx | Awx | Nw | Cwx | Ewx |
1 1 | 1 | 1 | 0 | 1 | 1 |
1 0 | 0 | 1 | 0 | 0 | 0 |
0 1 | 0 | 1 | 1 | 1 | 0 |
0 0 | 0 | 0 | 1 | 1 | 1 |
A tautology is a WFF that has value 1 (true) regardless of the values of its variables. For example, ApNp is a tautology because it is true regardless of the value of p. On the other hand, ApNq is not, because it has the value 0 for p=0, q=1.
You must determine whether or not a WFF is a tautology.
Input
Input consists of several test cases. Each test case is a single line containing a WFF with no more than 100 symbols. A line containing 0 follows the last case.
Output
For each test case, output a line containing tautology or not as appropriate.
Sample Input
ApNp ApNq 0
Sample Output
tautology题意:判断一个式子是否为重言式(永真式)大写字母代表逻辑运算符,小写字母代表逻辑变量。not
重点是对所有逻辑变量真假两种情况的组合,巧妙点在于用栈可以很好地进行逻辑运算而不用考虑下标,还能将运算结果入栈后准备下一次逻辑运算,最后剩下的一个逻辑值则为整个式子的逻辑值。如果为小写字母就入栈,大写字母则根据其要求将逻辑变量出栈,最后就是要注意从后往前遍历字符串,因为上来肯定是大写字母。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
stack<int> q;//定义栈
int P,Q,R,S,T;
bool judge(char c)//判断是否为逻辑变量
{
switch(c)
{
case 'p':q.push(P);return true;
case 'q':q.push(Q);return true;
case 'r':q.push(R);return true;
case 's':q.push(S);return true;
case 't':q.push(T);return true;
}
return false;
}
void operate(char c)//逻辑运算子函数
{
switch(c)
{
case 'K':
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
q.push(a&&b);
break ;
}
case 'A':
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
q.push(a||b);
break;
}
case 'N':
{
int a=q.top();
q.pop();
q.push(!a);
break;
}
case 'C':
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
q.push((!a)||b);
break;
}
case 'E':
{
int a=q.top();
q.pop();
int b=q.top();
q.pop();
q.push(a==b);
break;
}
}
}
int main()
{
char s[111];
while(scanf("%s",s)&&s[0]!='0')
{
int len=strlen(s);
int ans,flag=0;
for(P=0;P<=1;P++)
{
for(Q=0;Q<=1;Q++)
{
for(R=0;R<=1;R++)
{
for(S=0;S<=1;S++)
{
for(T=0;T<=1;T++)
{
for(int i=len-1;i>=0;i--)//注意要逆序遍历
{
if(!judge(s[i]))
operate(s[i]);
}
ans=q.top();
q.pop();
if(!ans)//如果有一次逻辑值为零则不是重言式,可以直接结束循环。
{
flag=1;
break;
}
}
if(flag)
break;
}
if(flag)
break;
}
if(flag)
break;
}
if(flag)
break;
}
if(flag)
printf("not\n");
else
printf("tautology\n");
}
return 0;
}