ZOJ-3025

4 篇文章 0 订阅

有了上题的基础,这题就轻松了,逻辑上比上题还简单一点点,因为基本上都有括号的保证,不用考虑优先级的问题,还是注意处理not的情况就可以,用个栈模拟,我这里直接用的数组来代替栈了

#include<stdio.h>
#include<string.h>

static int op[80], num[80], os, ns;
static int not[3] = { 2, 1, 0 }, and[3][3] = { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 1,
		2 } }, or[3][3] = { { 0, 1, 2 }, { 1, 1, 2 }, { 2, 2, 2 } };

static void calc_not()
{
	while (os && op[os - 1] == '-')
	{
		num[ns - 1] = not[num[ns - 1]];
		os--;
	}
}

static int calc(char *s, int p, int q, int r)
{
	int i, a, b, l = strlen(s);
	char c;
	os = ns = 0;
	for (i = 0; i < l; i++)
	{
		c = s[i];
		if (c == 'P' || c == 'Q' || c == 'R')
		{
			if (c == 'P')
				num[ns++] = p;
			else if (c == 'Q')
				num[ns++] = q;
			else if (c == 'R')
				num[ns++] = r;
			calc_not();
		}
		else if (c == '(' || c == '-')
			op[os++] = c;
		else if (c == ')')
		{
			while (op[os - 1] != '(')
			{
				a = num[--ns];
				b = num[--ns];
				if (op[os - 1] == '*')
					num[ns++] = and[a][b];
				else
					num[ns++] = or[a][b];
				os--;
			}
			os--;
			calc_not();
		}
		else if (c == '*' || c == '+')
			op[os++] = c;
		else
		{
			num[ns++] = c - '0';
			calc_not();
		}
	}
	return num[0];
}

int main()
{
	char s[81];
	int p, q, r;
	while (gets(s), strcmp(s, "."))
	{
		int total = 0;
		for (p = 0; p < 3; p++)
			for (q = 0; q < 3; q++)
				for (r = 0; r < 3; r++)
					if (calc(s, p, q, r) == 2)
						total++;
		printf("%d\n", total);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值