POJ3295 Tautology(枚举)

时间:2022-09-04 21:21:02

题目链接

分析:

最多有五个变量,所以枚举所有的真假值,从后向前借助于栈验证是否为永真式。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <stack> using namespace std; const int maxn = + ; stack<bool> S;
char s[maxn];
bool hash[], ans; void check(char pos) { if(s[pos] == 'N') {
bool x = S.top(); S.pop();
S.push(!x);
} else if(s[pos] >= 'p' && s[pos] <= 't') {
S.push(hash[s[pos]]);
} else {
bool x, y;
x = S.top(); S.pop();
y = S.top(); S.pop(); if(s[pos] == 'K') S.push(x&y);
else if(s[pos] == 'A') S.push(x|y);
else if(s[pos] == 'C') S.push(!x | y); //即蕴含
else if(s[pos] == 'E') S.push(!(x^y));
} } int main() {
//freopen("my.txt", "r", stdin);
while(scanf("%s", s) == ) {
if(s[] == '') break;
ans = true;
int i; for(i=; i<(<<); i++) {
hash['p'] = i & ;
hash['q'] = i & (<<);
hash['r'] = i & (<<);
hash['s'] = i & (<<);
hash['t'] = i & (<<); int pos = strlen(s)-; while(pos >= ) {
check(pos);
pos--;
} ans = S.top(); S.pop(); if(ans == false) { printf("not\n"); break; }
} if(i >= (<<)) printf("tautology\n");
} return ;
}

另一种写法

该写法参考自Disuss:http://poj.org/showmessage?message_id=168123(里面对于莫名其妙的错误还有讲解,不错)

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <stack> using namespace std; const int maxn = + ; char s[maxn];
int c_s, value; bool getval() {
bool t1, t2; switch(s[c_s++]) {
case 'p': return (value & (<<));
case 'q': return (value & (<<));
case 'r': return (value & (<<));
case 's': return (value & (<<));
case 't': return (value & (<<)); case 'N': return !getval();
case 'K': t1 = getval(); t2 = getval(); return t1 & t2;
case 'A': t1 = getval(); t2 = getval(); return t1 | t2;
case 'C': t1 = getval(); t2 = getval(); return (!t1 | t2);
case 'E': t1 = getval(); t2 = getval(); return (!(t1^t2));
}
} int main() {
// freopen("my.txt", "r", stdin);
while(scanf("%s", s) == ) {
if(s[] == '') break; for(value = ; value < (<<); value++){
c_s = ;
if(!getval()) { printf("not\n"); break; }
} if(value >= (<<)) printf("tautology\n");
} return ;
}