利用真值表法求取主析取范式以及主合取范式的实现(C++)
生活随笔
收集整理的這篇文章主要介紹了
利用真值表法求取主析取范式以及主合取范式的实现(C++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼如下:
#include <iostream> #include <stack> #include <string> #include <vector> using namespace std; const int N = 300; stack<char> s; stack<char> v; int seq; bool vis[N]; bool flag[N]; void dfs(int n); vector<int> ans_v; vector<int> 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<int> &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<char>t;while (!s.empty()){t.push(s.top());s.pop();}s = t;stack<char>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<char> s_s(s);stack<bool> 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; }運行示例:
總結
以上是生活随笔為你收集整理的利用真值表法求取主析取范式以及主合取范式的实现(C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cf战场模式怎么玩
- 下一篇: LED计数电路,5输入按键编码器,7段数