Tautology
构造法。。虽然我也不知道什么叫构造法
题目大意:
给定一个关系式,判断是否为重言式(永真式)
给定数据由一个字符串组成,其中包括,K A N C E p q r s t
其中K代表与运算 A代表或运算 N代表取反 C代表implies//Cab = (!a || b) E代表同或,,
然后小写字母代表逻辑变量
例如:
Np 就是对于逻辑变量p取反
ApNp即为p || !p 即为重言式
题目要求:
对于给定的表达式,逻辑变量可以取 0 1 ,如果一个逻辑表达式不管逻辑变量如何取值,表达式
都为重言式,那么就是个Tautology 否则输出not
大概意思在所有的可能的表达式取法种,都为重言式,输出Tautology 否则输出 not
note: 如果一个表达式种多次出现了q 或者其他任意字母,那么他们的逻辑取值必须一样
//真坑了我好大一会
例如题目给定的第一个Sample
ApNp 即为 p || !p 肯定是重言式, 所以打印Tautology
思路:
将其中所有的逻辑变量全部替换成0 和 1 把所有情况都找一下, 如果全为重言式,即为Tautology
否则not
刚开始递归等各种方法来找到所有状态/情况 发现超时,最后解决方案:
题目最多给了5个逻辑变量,也就是说最多有32种情况
列举出来,然后挨个尝试
代码
#include <iostream>
#include <stack>
#include <cstring>
std:: string str;
int len;
bool res = true ;
int qrr[ 5 ] ;
bool judge ( char a)
{
if ( a >= 'A' && a <= 'Z' ) return true ;
return false ;
}
bool vj ( std:: string a)
{
int temp = 0 ;
std:: stack< int > ar;
for ( int i = len - 1 ; i >= 0 ; -- i)
{
if ( ! judge ( a[ i] ) ) ar. push ( a[ i] - '0' ) ;
else
{
char ch = a[ i] ;
if ( ch == 'N' )
{
int front = ar. top ( ) ;
ar. pop ( ) ;
ar. push ( ! front) ;
}
else if ( ch == 'K' )
{
int front1 = ar. top ( ) ;
ar. pop ( ) ;
int front2 = ar. top ( ) ;
ar. pop ( ) ;
ar. push ( front1 && front2) ;
}
else if ( ch == 'A' )
{
int front1 = ar. top ( ) ;
ar. pop ( ) ;
int front2 = ar. top ( ) ;
ar. pop ( ) ;
ar. push ( front1 || front2) ;
}
else if ( ch == 'C' )
{
int front1 = ar. top ( ) ;
ar. pop ( ) ;
int front2 = ar. top ( ) ;
ar. pop ( ) ;
ar. push ( ! front1 || front2) ;
}
else if ( ch == 'E' )
{
int front1 = ar. top ( ) ;
ar. pop ( ) ;
int front2 = ar. top ( ) ;
ar. pop ( ) ;
ar. push ( ( front1 == front2) ) ;
}
}
}
temp = ar. top ( ) ;
ar. pop ( ) ;
return temp;
}
void dfs ( std:: string arr, bool skip, int q[ ] )
{
if ( skip) return ;
for ( int i = 0 ; i < len; ++ i)
{
if ( str[ i] == 'p' ) arr[ i] = q[ 0 ] + '0' ;
else if ( str[ i] == 'q' ) arr[ i] = q[ 1 ] + '0' ;
else if ( str[ i] == 'r' ) arr[ i] = q[ 2 ] + '0' ;
else if ( str[ i] == 's' ) arr[ i] = q[ 3 ] + '0' ;
else if ( str[ i] == 't' ) arr[ i] = q[ 4 ] + '0' ;
}
if ( ! vj ( arr) )
{
res = false ;
skip = true ;
}
return ;
}
void init ( int i, int value)
{
if ( ! res) return ;
qrr[ i] = value;
if ( i > 3 )
{
dfs ( str, false , qrr) ;
return ;
}
init ( i+ 1 , 0 ) ;
init ( i+ 1 , 1 ) ;
return ;
}
int main ( )
{
while ( std:: cin >> str && str[ 0 ] != '0' )
{
res = true ;
memset ( qrr, 0 , sizeof qrr) ;
len = str. size ( ) ;
init ( 0 , 0 ) ;
init ( 0 , 1 ) ;
if ( res) std:: cout << "tautology" << std:: endl;
else std:: cout << "not" << std:: endl;
}
return 0 ;
}