实验内容:编程实现关系性质的判断
提示:
¨
用矩阵表示二元关系
¨
通过矩阵的特征判断二元关系所具有的性质
¨
运用二维数组实现矩阵的输入,然后判断自反性,反自反性,对称性,反对称性,传递性
#include<iostream>
using namespace std;
void main()
{
int N;
int ElemNum = 0;
cout << "请输入矩阵的维数:" << endl;
cin >> N;
//根据维数生成矩阵
int** p = (int**)malloc(N * sizeof(int*));
for (int i = 0; i < N; i++)
{
p[i] = (int*)malloc(N * sizeof(int*));
}
//矩阵数据输入
cout << "请输入矩阵的数据:" << endl;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cin >> p[i][j];
if (p[i][j] == 1)
ElemNum++;
}
}
//自反性
cout << "自反性:";
bool self_reflexivity = true;//默认为自反
for (int i = 0; i < N; i++)
{
if (p[i][i] != 1)//遍历对角线元素,有一个不为1则说明不存在自反
{
self_reflexivity = false;
break;
}
}
if (self_reflexivity == true)
cout << "具有自反性!" << endl;
else if (self_reflexivity == false)
cout << "不具有自反性。" << endl;
//反自反性
cout << "反自反性:";
bool irreflexive = true;//默认具有
for (int i = 0; i < N; i++)
{
if (p[i][i] != 0)//遍历对角线元素,对角线必须全为0说明具有反自反性
{
irreflexive = false;
break;
}
}
if (irreflexive == true)
cout << "具有反自反性!" << endl;
else
cout << "不具有反自反性。" << endl;
//对称性
cout << "对称性:";
bool symmetry = true;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (p[i][j] == 1 && p[i][j] != p[j][i])
{
symmetry = false;
}
}
}
if (symmetry == true)
cout << "具有对称性!" << endl;
else
cout << "不具有对称性。" << endl;
//反对称性
cout << "反对称性:";
bool irsymmetry = true;
for (int i = 0; i < N; i++)
{
for (int j = 0; j <= i; j++)//寻找对角线的一侧
{
if (i != j && p[i][j] == 1 && p[i][j] == p[j][i])
{
irsymmetry = false;
}
}
}
if (irsymmetry == true)
cout << "具有反对称性!" << endl;
else
cout << "不具有反对称性。" << endl;
//传递性
cout << "传递性:";
bool delivery = true;
for (int i = 0; i < N; i++)
{
if (ElemNum == 1)//只有一个元素时
break;
for (int j = 0; j < N; j++)
{
for (int k = 0; k < N; k++)
{
if (p[i][j] == 1 && p[j][k] == 1)//具有可传递元素
{
if (p[i][k] != 1)
{
delivery = false;
}
}
}
}
}
if (delivery == true)
cout << "具有传递性!" << endl;
else
cout << "不具有传递性。" << endl;
}