代码如下:
#include#include #include #include using namespace std; const int N = 300; stack s; stack v; int seq; bool vis[N]; bool flag[N]; void dfs(int n); vector ans_v; vector ans_vf; void printMenu() { cout << "代码其实有点不健壮,需要用括号来手动处理优先级!" << endl; cout << "比如:!!!(a&b&c) 要写成!(!(!(a&b&c)))" << endl; cout << "比如:!(a&b)->c 要写成 (!(a&b))>c" << endl; cout << "合取& 析取| 非! 条件> 双条件~ 括号() " << endl; cout << endl; } void printAns(vector &ans_v, char f, char v) { for (int i = 0; i < ans_v.size(); i++) { cout << f << ans_v[i]; if (i != ans_v.size() - 1) { cout << v; } } cout << endl; } void calculator(int n, string &str) { str = '(' + str + ')'; for (int i = 0; i < str.length(); i++) { char tmp = str[i]; if (tmp >= 'a' && tmp <= 'z') { vis[tmp - 'a'] = true; s.push(tmp); } else if (tmp == '(') { v.push(tmp); } else if (tmp == ')') { while (v.top() != '(') { s.push(v.top()); v.pop(); } v.pop(); } else { v.push(tmp); } } stack t; while (!s.empty()) { t.push(s.top()); s.pop(); } s = t; stack h(s); while (!h.empty()) { cout << h.top(); h.pop(); } cout << endl; dfs(0); cout << "主合取范式为:" << endl; printAns(ans_v, 'm', '&'); cout << "主析取范式为:" << endl; printAns(ans_vf, 'M', '|'); } void dfs(int n) { if (n == 26) { stack s_s(s); stack s_t; while (!s_s.empty()) { if (s_s.top() == '&' || s_s.top() == '|' || s_s.top() == '~' || s_s.top() == '>') { if (s_s.top() == '&') { s_s.pop(); bool a2 = s_t.top(); s_t.pop(); bool a1 = s_t.top(); s_t.pop(); bool ans = a2 && a1; s_t.push(ans); } else if (s_s.top() == '|') { s_s.pop(); bool a2 = s_t.top(); s_t.pop(); bool a1 = s_t.top(); s_t.pop(); bool ans = a2 || a1; s_t.push(ans); } else if (s_s.top() == '>') { s_s.pop(); bool a2 = s_t.top(); s_t.pop(); bool a1 = s_t.top(); s_t.pop(); if (a1 == true && a2 == true) { s_t.push(true); } else if (a1 == true && a2 == false) { s_t.push(false); } else if (a1 == false) { s_t.push(true); } } else if (s_s.top() == '~') { s_s.pop(); bool a2 = s_t.top(); s_t.pop(); bool a1 = s_t.top(); s_t.pop(); if (a1 == a2) { s_t.push(true); } else s_t.push(false); } } else if (s_s.top() == '!') { s_s.pop(); bool tmp = !s_t.top(); s_t.pop(); s_t.push(tmp); } else { s_t.push(flag[s_s.top() - 'a']); s_s.pop(); } } for (int i = 0; i < 26; i++) { if (vis[i]) { cout << char(i + 'a') << "=" << flag[i] << " "; } } if (s_t.top()) { ans_v.push_back(seq); cout << "ans=true" << endl; } else { ans_vf.push_back(seq); cout << "ans=false" << endl; } seq++; return; } if (vis[n]) { for (int i = 0; i <= 1; i++) { flag[n] = i; dfs(n + 1); } } else { dfs(n + 1); } } int main() { int n; string str; printMenu(); cout << "请先输入式子含有的变量个数" << endl; cin >> n; cout << "按格式输入式子" << endl; cin >> str; calculator(n, str); return 0; }
运行示例:



