ZOJ-3025

来源:互联网 发布:东风(十堰)整合优化 编辑:程序博客网 时间:2024/04/19 19:21

有了上题的基础,这题就轻松了,逻辑上比上题还简单一点点,因为基本上都有括号的保证,不用考虑优先级的问题,还是注意处理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];elsenum[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;}


0 0
原创粉丝点击