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 WFFsif w is a WFF, Nw is a WFFif w and x are WFFs, Kwx, Awx, Cwx, and Ewx are WFFs.The meaning of a WFF is defined as follows:
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.Definitions of K, A, N, C, and E
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 1A 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 0Sample Output
tautology not题意:给你5个bool数,还有5个自定义类型的的运算,如果5个数的真值表(都是1的话输出tautology,否则输出not),也即给出的式子是永真式;
解题思路:
用5层for(0, 1)循环,取所有可能的值
从字符串WFF的末尾开始依次向前读取字符。
构造一个栈stack,当遇到逻辑变量 p, q, r, s ,t 则将其当前的值压栈;
遇到 N 则取栈顶元素进行非运算,运算结果的值压栈;
遇到K, A, C, E则从栈顶中弹出两个元素进行相应的运算,将结果的值压栈。
由于输入是合法的,当字符串WFF扫描结束时,栈stack中只剩一个值,该值就是逻辑表达式WFF的值。
#include <stdio.h> #include <string.h> #include <stack> using namespace std; int main() { stack<bool> wff; char w[105]; int p,q,r,s,t; while(~scanf("%s",w) && w[0]!='0'){ bool flag_go=false; int len=strlen(w); bool a_w, b_w; 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++){ for(int i=len-1; i>=0; i--){ switch (w[i]) { case 'p': wff.push(p); break; case 'q': wff.push(q); break; case 'r': wff.push(r); break; case 's': wff.push(s); break; case 't': wff.push(t); break; case 'K': a_w = wff.top(); wff.pop(); b_w = wff.top(); wff.pop(); wff.push(a_w && b_w); break; case 'A': a_w=wff.top(); wff.pop(); b_w=wff.top(); wff.pop(); wff.push(a_w || b_w); break; case 'N': a_w=wff.top(); wff.pop(); wff.push(!a_w); break; case 'C': a_w=wff.top(); wff.pop(); b_w=wff.top(); wff.pop(); wff.push((!a_w) || b_w); break; case 'E': a_w=wff.top(); wff.pop(); b_w=wff.top(); wff.pop(); wff.push(a_w == b_w ? 1 : 0); } } if(!wff.top()){ flag_go=true; break; } } if(flag_go) break; } if(flag_go) break; } if (flag_go) break; } if(flag_go) break; } if (wff.top()) { printf("tautology\n"); } else{ printf("not\n"); } wff.pop(); } return 0; }