输出命题公式的真值表
问题描述:
先输入一个正整数 n(n 小于等于 10),表示共有 n 个命题变元,再输入一个类
似于逆波兰表达式的字符串表示一个命题公式,约定在该字符串中用一位的十进
制数表示一个命题变元,用 a、o、n、i、e 分别表示且、或、非、蕴含、等值,
用类似于逆波兰表达式形式的字符串表示的命题公式的真值表波兰表达式(即二
元运算,两个操作数在前,运算符在后;一元运算,一个操作数在前,运算符在
后)。
输入
先输入一个小于等于 10 的正整数 n,再输入一个字符串。
输出
输出该字符串表示的命题公式的真值表。
提示:
如果用 P、Q、R 分别表示这三个命题变元的话,
输入数据 01a2i 表示的命题公式是:((P∧Q)→R)
输入数据 012ia 表示的命题公式是:(P∧(Q→R))
输入数据 0n 表示的命题公式是:┐P
输入样例
3
01a2i
输出样例
0 0 0 1
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 1
代码:
#include<iostream>
#include<stack>
//#include<cstring>
#include<string>
using namespace std;
//char str[20];
string str;
int ans[20];
stack<char>s;
int len;
int n;
//完成真值表的运算,类似于中缀转后缀求表达式的值。
void run()
{
while(!s.empty()){
s.pop();
}
char s1,s2,s3;
int top=1;
for(int i=0;i<len;i++){
if(str[i]=='a'){
s1=s.top();
s.pop();
s2=s.top();
s.pop();
if(s1=='0'||s2=='0'){
//s3='0';
s.push('0');
}
else{
s.push('1');
}
}
else if(str[i]=='o'){
s1=s.top();
s.pop();
s2=s.top();
s.pop();
if(s1=='0'&&s2=='0'){
//3='1';
s.push('0');
}
else{
//s3='0';
s.push('1');
}
}
else if(str[i]=='i'){
s1=s.top();
s.pop();
s2=s.top();
s.pop();
if(s2=='1'&&s1=='0'){
//s3='0';
s.push('0');
}
else{
//s3='1';
s.push('1');
}
}
else if(str[i]=='e'){
s1=s.top();
s.pop();
s2=s.top();
s.pop();
if(s1==s2){
s3='1';
s.push('1');
}
else{
s3='0';
s.push('0');
}
}
else if(str[i]=='n'){
s1=s.top();
if(s1=='0'){
//s3='1';
s.push('1');
}
else{
//s3='0';
s.push('0');
}
}
else{
s3=ans[top++]+'0';
s.push(s3);
}
}
}
void print_info(){
for(int i=1;i<=n;i++){
cout<<ans[i]<<" ";
//printf("%d ",ans[i]);
}
cout<<s.top()<<endl;
//printf("%c",s.top());
}
//深度搜索,利用递归回退把所有情况的真值都考虑进去
void dfs(int r){
if(r>n){run();print_info();return;}
else{
for(int i=0;i<2;i++){
ans[r]=i;
dfs(r+1);//刚开始这里写的是r++,相当于r=r+1,没能成功调用dfs()函数,找了好长时间错误,没想到在这错了!
}
}
}
int main(){
cin>>n;
cin>>str;
//scanf("%s",str);
//len=strlen(str);//strlen()函数的头文件是<cstring>,用的是字符串的函数,而不是<string>头文件
len=str.length();//而length()函数的头文件在<string>中,用的是容器中的函数。
dfs(1);
return 0;
}