性質判斷原理和編碼思路ios
關於自反性、對稱性、傳遞性、反自反性和反對稱性的定義不在此贅述。自反性對稱性和反自反反對稱比較簡單,關於傳遞性的判斷,咱們使用Warshall算法計算傳遞閉包,當傳遞閉包對應的關係矩陣與原關係矩陣一致時,咱們認爲它是知足傳遞性的。算法
關於編碼思路,作個提綱: 閉包
一共6個函數,前5個函數分別表示對5個性質的判斷,第6個是Warshall算法函數,實現封裝機制,在第3個判斷傳遞性的函數中直接調用函數6便可。函數
關於輸入輸出的說明:第一次輸入的是集合元素個數,第二個輸入的是關係個數,而後接着輸入關係,輸出結果判斷,我將在下面以例子說明。flex
實現代碼:編碼
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <vector> #include <string.h> #include <cstring> using namespace std; const int LEN = 100; bool Reflexivity(); //自反性 bool Symmetry(); //對稱性 bool Transmission(); //傳遞性 bool Irreflexivity(); //反自反性 bool Irsymmetry(); //反對稱性 void Warshall(); //Warshall算法 int num; int relation_num; int relation[LEN][LEN]; int A[LEN][LEN]; int main() { while(cin >> num && cin >> relation_num) { int tmp1, tmp2; memset(relation, 0, sizeof(relation)); memset(A, 0, sizeof(A)); for(int i = 1; i <= relation_num; i++) { cin >> tmp1 >> tmp2; relation[tmp1][tmp2] = 1; } if(Reflexivity()) { cout << "Meet the reflexive..." ; } else { cout << "Not meet the reflexive..."; } cout << endl; if(Symmetry()) { cout << "Meet the Symmetry..."; } else { cout << "Not meet the Symmetry..."; } cout << endl; if(Transmission()) { cout << "Meet the Transmission..."; } else { cout << "Not meet the Transmission..."; } cout << endl; if(Irreflexivity()) { cout << "Meet the Irreflexivity..."; } else { cout << "Not meet the Irreflexivity..."; } cout << endl; if(Irsymmetry()) { cout << "Meet the Irsymmetry.."; } else { cout << "Not meet the Irsymmetry..."; } cout << endl; } return 0; } bool Reflexivity() //自反性 { // bool flag = false; for(int i = 1; i <= num; i++) { if(relation[i][i] != 1) { return false; } } return true; } bool Symmetry() //對稱性 { for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(relation[i][j] != relation[j][i]) { return false; } } } return true; } bool Transmission() //傳遞性 { Warshall(); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(A[i][j] != relation[i][j]) { return false; } } } return true; } bool Irreflexivity() //反自反性 { for(int i = 1; i <= num; i++) { if(relation[i][i] == 1) { return false; } } return true; } bool Irsymmetry() //反對稱性 { for(int i = 1; i <= num - 1; i++) { for(int j = i + 1; j <= num; j++) { if(relation[i][j] == 1 && relation[j][i] == 1) { if(i != j) { return false; } } } } return true; } void Warshall() //Warshall算法 { for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { A[i][j] = relation[i][j]; } } for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(A[j][i] == 1) { for(int k = 1; k <= num; k++) { A[j][k] = A[j][k] + A[i][k]; if(A[j][k] >= 1) { A[j][k] = 1; } } } } } }
由於集合元素個數有4個,因此輸入4spa
由於關係個數共8個,因此接着輸入8code
接着輸入ci
1 1 string
1 3
2 2
....
等,一共8組數據。
運行示例以下: