題目:根據某一集合元素以及關係矩陣,判斷其滿足什麼特性,輸出滿足的特性,再求此集合的閉包。
舉例:以集合{1,2,3,4}爲例。關係矩陣爲:[[1,0,1,0],[0,1,0,0],[1,0,1,1],[0,0,1,1]]。
程序代碼
//集合 A = {1,2,3,4}
//關係矩陣爲:
//1 0 1 0
//0 1 0 0
//1 0 1 1
//0 0 1 1
//滿足:自反性、對稱性
//集合 A 的閉包:
//1 0 1 1
//0 1 0 0
//1 0 1 1
//1 0 1 1
#include <iostream>
using namespace std;
#define MAX 1000
bool flag_ref, flag_irr, flag_sym, flag_dis, flag_tra; //判斷自反性、反自反性、對稱性、反對稱性、傳遞性的 flag
int matrix[MAX][MAX];
int n;
//自反性
void Reflexive(){
flag_ref = true;
for(int i = 0; i < n; ++i){
if(matrix[i][i] != 1){ //只要有一個對角線元素爲 0:即不滿足
flag_ref = false;
break;
}
}
}
//反自反性
void Irreflexive(){
flag_irr = true;
for(int i = 0; i < n; ++i){
if(matrix[i][i] == 1){ //只要有一個對角線元素爲 1:即不滿足
flag_irr = false;
break;
}
}
}
//對稱性
void Symmetrical(){
flag_sym = true;
for(int i = 0 ; i < n; ++i){
for(int j = 0; j < n; ++j){
if(matrix[i][j] != matrix[j][i]){ //只要有一對對稱元素不相等:即不滿足對稱性
flag_sym = false;
break;
}
}
}
}
//反對稱性
void Dissymmetrical(){
flag_dis = true;
for(int i = 0 ; i < n; ++i){
for(int j = 0; j < n; ++j){
if(matrix[i][j] == matrix[j][i]){ //只要有一對對稱元素相等:即不滿足反對稱性
flag_dis = false;
break;
}
}
}
}
//傳遞性
void Transitive(){
flag_tra = true;
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
for(int k = 0; k < n; ++k){
if(matrix[i][j] && matrix[j][k] && !matrix[i][k]){ //前兩個爲 1,第三個爲 0
flag_tra = false;
break;
}
}
}
}
}
//求閉包
void Closure(){
for(int i = 0; i < n; ++i){ //列
for(int j = 0; j < n; ++j){ //行
if(matrix[j][i] == 1){
for(int k = 0 ; k < n; ++k){
if(matrix[j][k] == 0 && matrix[i][k] == 0){
matrix[j][k] = 0;
}
else if(matrix[j][k] == 0 && matrix[i][k] == 1){
matrix[j][k] = 1;
}
else if(matrix[j][k] == 1 && matrix[i][k] == 0){
matrix[j][k] = 1;
}
else if(matrix[j][k] == 1 && matrix[i][k] == 1){
matrix[j][k] = 1;
}
}
}
}
}
}
int main(){
int a[MAX];
cout << "Please input the n of the set:" << endl;
cin >> n;
cout << "Please input the elements of the set:" << endl;
for(int i = 0; i < n; ++i){
cin >> a[i];
}
cout << "The set A = {";
for(int i = 0; i < n-1; ++i){
cout << a[i] << ",";
}
cout << a[n-1] << "}" << endl;
cout << "Please input the Relation matrix:" << endl;
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
cin >> matrix[i][j];
}
}
cout << endl;
Reflexive();
Irreflexive();
Symmetrical();
Dissymmetrical();
Transitive();
cout << "The set A has some characters:" << endl;
if(flag_ref == true){
cout << "自反性" << endl;
}
if(flag_irr == true){
cout << "反自反性" << endl;
}
if(flag_sym == true){
cout << "對稱性" << endl;
}
if(flag_dis == true){
cout << "反對稱性" << endl;
}
if(flag_tra == true){
cout << "傳遞性" << endl;
}
cout << endl;
cout << "Output the Closure of the set A:" << endl;
Closure();
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}