实验原理及内容
实验原理:遍历二元关系中的关系矩阵,判断该二元关系的性质。先将二元关系中的序偶转换成该二元关系对应的关系矩阵,利用关系矩阵和二元关系的性质来判断。
实验内容:首先输入要求二元关系的集合所对应的全集中的元素个数以及二元关系所包含的序偶,屏幕输出该全集以便使用者观看。一共6个函数,前5个函数分别表示对5个性质的判断,第6个是Warshall算法函数,实现封装机制,在第3个判断传递性的函数中直接调用函数6即可。
输入输出的说明:第一次输入的是集合元素个数,第二个输入的是关系个数,然后接着输入二元关系内的序偶<x,y>,输出结果判断。
#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()
{
cout<<"请输入元素个数"<<endl;
cin >> num;
cout<<"请输入相应的"<<num<<"个元素的集合对应的序偶数个数";
cin >> relation_num;
while( num && relation_num)
{
int tmp1, tmp2;
memset(relation, 0, sizeof(relation)); //初始化函数
memset(A, 0, sizeof(A)); //初始化函数
cout<<"请输入二元关系";
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;
break;
}
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(); //先用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;
}
else A[j][k]=0;
}
}
}
}
}
运行结果: