时间限制:1 s 内存限制:256 MB 测试点数:10
【题目描述】
由大写英文字母和符号~、 *、+、()
组成逻辑表达式,其中三个符号分别表示逻辑非、与、或运算,英文字母表示变量,变量有两种可能的取值,FALSE(0)或TRUE(1),~、*、+、括号()可改变表达式的运算次序,且可以嵌套。 编一个程序计算逻辑表达式的值。
【输入格式】
输入为若干行 第一行字符串s(1<=length<=200);
第二行为一个整数n(1<=n<=26);n表示上述逻辑表达式中逻辑变量的个数;
第3–2+n行为每个逻辑变量的值,其中变量名均为一个大写字母。
【输出格式】
输出一个逻辑值(TRUE 或 FALSE)
【样例输入】
(A+B)*(B+C)
3
A 1
B 0
C 0
【样例输出】
FALSE
#include<bits/stdc++.h>
using namespace std;
int calculate(int m, int n, char t) {
switch (t) {
case '+':
return (m == 1 || n == 1) ? 1 : 0;
case '*':
return (m == 1 && n == 1) ? 1 : 0;
}
}
int main() {
char s[202];
stack<int> number;
stack<char> operate;
scanf("%s", s);
map<char, int> value;
map<char, int> importance;
int n;
cin >> n;
importance['\0'] = 0;
importance['+'] = 1;
importance['*'] = 2;
importance['~'] = 3;
while (n--) {
char a;
int b;
cin >> a >> b;
value[a] = b;
}
char b = '\0';
int len = strlen(s);
for (int i = 0; i <= len; i++) {
if (i == len && operate.empty())
break;
if (s[i] >= 'A' && s[i] <= 'Z')
number.push(value[s[i]]);
else if (s[i] == '(') {
operate.push(s[i]);
b = '\0';
} else if (s[i] == ')') {
if (operate.top() != '(' && operate.top() != '~') {
int nn = number.top();
number.pop();
int mm = number.top();
number.pop();
number.push(calculate(mm, nn, operate.top()));
operate.pop();
} else {
int number0 = number.top();
number.pop();
number.push((number0 == 1) ? 0 : 1);
operate.pop();
}
operate.pop();
if (operate.empty())
b = '\0';
else
b = operate.top();
} else {
int flag = 0;
if (importance[s[i]] > importance[b]) {
operate.push(s[i]);
b = s[i];
} else {
while (importance[s[i]] <= importance[b] && (!operate.empty()) && b != '(') {
if (b == '~') {
if (s[i] == '~') {
operate.pop();
if (operate.empty())
b = '\0';
else
b = operate.top();
flag = 1;
continue;
} else {
int number0 = number.top();
number.pop();
number.push((number0 == 1) ? 0 : 1);
operate.pop();
}
} else {
int nn = number.top();
number.pop();
int mm = number.top();
number.pop();
number.push(calculate(mm, nn, operate.top()));
operate.pop();
}
if (operate.empty())
b = '\0';
else
b = operate.top();
}
if (flag)
continue;
operate.push(s[i]);
b = operate.top();
}
}
if (b == '(')
b = '\0';
}
if (number.top())
printf("TRUE");
else
printf("FALSE");
return 0;
}