逻辑表达式运算

逻辑表达式运算时间限制 1s 内存限制 256MB 测试点数 10 题目描述 由大写英文字母和符号 组成逻辑表达式 其中三个符号分别表示逻辑非 与 或运算 英文字母表示变量 变量有两种可能的取值 FALSE 0 或 TRUE 1 括号 可改变表达式的运算次序 且可以嵌套 编一个程序计算逻辑表达式的值 输入格式 输入为若干行第一行字符串 s 1 lt l

【样例输入】 (A+B)*(B+C) 3 A 1 B 0 C 0 【样例输出】 FALSE 
#include 
     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; } 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/229937.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月16日 下午3:31
下一篇 2026年3月16日 下午3:31


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号