1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| #include <cstring> #include <iostream> #include <map> #include <stack> #include <vector> using namespace std;
map<char, int> prior = {{'!', 5}, {'&', 4}, {'|', 3}};
bool isOperator(char op) { if (op == '|' || op == '&' || op == '!') return true; return false; }
string getPostfix(string infix) { stack<char> s; string postfix; for (int i = 0; i < infix.size(); i++) { char tmp = infix[i]; if (isOperator(tmp)) { while (!s.empty() && isOperator(s.top()) && prior[s.top()] >= prior[tmp]) { postfix.push_back(s.top()); s.pop(); } s.push(tmp); } else if (tmp == '(') { s.push(tmp); } else if (tmp == ')') { while (s.top() != '(') { postfix.push_back(s.top()); s.pop(); } s.pop(); } else if (isalpha(tmp)) postfix.push_back(tmp); } while (!s.empty()) { postfix.push_back(s.top()); s.pop(); } return postfix; }
bool Caculate(string postfix) { stack<int> s; bool left, right; bool flag; for (int i = 0; i < postfix.size(); i++) { char c = postfix[i]; if (c == '0' || c == '1') { s.push(c - '0'); continue; } else if (c == '!') { flag = s.top(); s.pop(); s.push(!flag); continue; } right = s.top(); s.pop(); left = s.top(); s.pop(); if (c == '|') { s.push(left | right); continue; } else if (c == '&') { s.push(left & right); continue; } } return s.top(); }
void Print(string infix) { string postfix = getPostfix(infix); vector<char> v; for (int i = 0; i < postfix.size(); i++) if (isalpha(postfix[i])) v.push_back(postfix[i]); v.erase(unique(v.begin(), v.end()), v.end());
for (int i = 0; i < v.size(); i++) printf("%5c", v[i]); printf(" %s\n", infix.c_str());
for (int i = 0; i < (1 << v.size()); i++) { string tmp = postfix; for (int k = 0; k < v.size(); k++) printf("%5d", 1 & (i >> k)); int j = 0; while (j < tmp.size()) { if (isalpha(tmp[j])) { int index = find(v.begin(), v.end(), tmp[j]) - v.begin(); tmp[j] = (char)((int)(1 & (i >> index)) + '0'); } j++; } printf("%5d\n", Caculate(tmp)); } return; }
int main() { string infix; printf("请您输入合法表达式(&表示合取,|表示析取,!表示非)\n"); while (cin >> infix) { Print(infix); printf("请您输入合法表达式(&表示合取,|表示析取,!表示非)\n"); } return 0; }
|