POJ 3295 构造栈计算表达式的值

大致题意:

输入由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

问这个逻辑表达式是否为永真式。

#include<iostream>
using namespace std;
int count=0;
 struct Stack
{
	int value;
}stack[101];
int N(int x)
{
	return !x;
}
int E(int x,int y)
{
	return x==y;
}
int C(int x,int y)
{
	return (!x)||y;
}
int K(int x,int y)
{
	return x&&y;
}
int A(int x,int y)
{
	return x||y;
}
void Insert (int num)
{
	stack[count].value=num;
	count++;
}
int  Pop()
{
	int x;
	x=stack[count-1].value;
	count--;
	return x;
}
bool isvalue(char ch,int p,int q,int r,int s,int t)
{
	switch (ch)
	{
	case 'p':Insert(p);
		return true;
	case 'q':Insert(q);
		return true;
	case 'r':Insert(r);
		return true;
	case 's':Insert(s);
		return true;
	case 't':Insert(t);
		return true;
	}
	return false;
}
void compute(char ch)
{
	int x,y;
	switch (ch)
	{
	case 'K':
		x=Pop();
		y=Pop();
		Insert(K(x,y));
		break;
	case 'A':
		x=Pop();
		y=Pop();
		Insert(A(x,y));
		break;
	case 'C':
		x=Pop();
		y=Pop();
		Insert(C(x,y));
		break;
	case 'E':
		x=Pop();
		y=Pop();
		Insert(E(x,y));
		break;
	case 'N':
		x=Pop();
		Insert(N(x));
		break;
	}
}
int main(int argc,char *argv[])
{
	char WFF[101];
	int length,i;
	int p,q,r,s,t;
	int end;
	bool flag;
	memset(stack,0,sizeof(stack));
	while (cin>>WFF&&WFF[0]!='0')
	{
		length=strlen(WFF);
		flag=true;
		for (p=0;p<=1;p++)
		{
			for (q=0;q<=1;q++)
			{
				for (r=0;r<=1;r++)
				{
					for (s=0;s<=1;s++)
					{
						for (t=0;t<=1;t++)
						{
							i=length-1;
							while (i>=0)
							{
								if (!isvalue(WFF[i],p,q,r,s,t))
								{
									compute(WFF[i]);
								}
								i--;
							}
							end=stack[count-1].value;
							count--;
							if (!end)
							{
								flag=false;
								break;
							}
						}
					}
				}
			}
		}
		if (flag==true)
		{
			cout<<"tautology"<<endl;
		} 
		else
		{
			cout<<"not"<<endl;
		}
	}
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值