POJ 3295 Tautology
[★★☆☆☆]枚举
题目大意:
输入由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:输入格式保证是合法的样例
输入:
ApNp
ApNq
0输出:
tautology
not解题思路:
水题,我用的是二叉树做的,我看到有人用stack做,没什么区别。
我第一次写用先序遍历树看有没有冲突,如果有冲突就是重言式,结果TLE了。发现可以直接枚举,需要注意的地方就是if判断的时候先用临时变量保存bool值,防止超时。代码
#include <iostream>
using namespace std;
struct TNode {
char c;
TNode *l;
TNode *r;
};
int ct[5];
bool crtT(TNode *&p) {
char c;
cin >> c;
if (c == '0') return 0;
if (c == 'K' || c == 'A' || c == 'C' || c == 'E'){
p->c = c;
p->l = new TNode;
crtT(p->l);
p->r = new TNode;
crtT(p->r);
}
else if (c == 'N') {
p->c = c;
p->l = new TNode;
crtT(p->l);
p->r = NULL;
}
else {
p->c = c;
p->l = NULL;
p->r = NULL;
}
return 1;
}
bool Z(TNode *p) {
char c = p->c;
if (c == 'K') {
bool pl = Z(p->l);
bool pr = Z(p->r);
if (pl==1 && pr==0) return 0;
if (pl==0 && pr==1) return 0;
if (pl==0 && pr==0) return 0;
if (pl==1 && pr==1) return 1;
}
if (c == 'A') {
bool pl = Z(p->l);
bool pr = Z(p->r);
if (pl==0 && pr==0) return 0;
if (pl==1 && pr==0) return 1;
if (pl==0 && pr==1) return 1;
if (pl==1 && pr==1) return 1;
return 0;
}
if (c == 'N') {
bool pl = Z(p->l);
if (pl==1) return 0;
if (pl==0) return 1;
return 0;
}
if (c == 'C') {
bool pl = Z(p->l);
bool pr = Z(p->r);
if (pl==1 && pr==0) return 0;
if (pl==1 && pr==1) return 1;
if (pl==0 && pr==1) return 1;
if (pl==0 && pr==0) return 1;
return 0;
}
if (c == 'E') {
bool pl = Z(p->l);
bool pr = Z(p->r);
if (pl==1 && pr==0) return 0;
if (pl==0 && pr==1) return 0;
if (pl==1 && pr==1) return 1;
if (pl==0 && pr==0) return 1;
return 0;
}
if (c == 'p') {
return ct[0];
}
if (c == 'q') {
return ct[1];
}
if (c == 'r') {
return ct[2];
}
if (c == 's') {
return ct[3];
}
if (c == 't') {
return ct[4];
}
return 0;
}
bool y0(TNode *T) {
for (int i1 = 0; i1 <= 1; i1++) {
ct[0] = i1;
for (int i2 = 0; i2 <= 1; i2++) {
ct[1] = i2;
for (int i3 = 0; i3 <= 1; i3++) {
ct[2] = i3;
for (int i4 = 0; i4 <= 1; i4++) {
ct[3] = i4;
for (int i5 = 0; i5 <= 1; i5++) {
ct[4] = i5;
if (Z(T) == 0) return 1;
}
}
}
}
}
return 0;
}
int main() {
TNode *T = new TNode;
while (crtT(T)){
if (y0(T)) cout << "not" << endl;
else cout << "tautology" << endl;
}
return 0;
}