利用矩阵判断传递性(二元关系,离散数学)

参考网址:http://www.docin.com/p-423233678.html

方法一:利用(复合矩阵法)(矩阵乘法)(之前学的线性代数终于用上了大笑

思路:设M是R的关系矩阵,若M*M为M的子集,则R具有传递性。

判断方法:计算M*M,M*M为M的子集的意思是,在方阵对应的同行同列的位置,若对于M,该数为0,则对于M*M,该数必为零,否则R不具有传递性。即:若M中的a[i][j] == 0, 则必有M*M中的c[i][j] == 0

代码如下:

#include <iostream>
using namespace std;
const int maxn = 100;
int a[maxn][maxn], c[maxn][maxn];

int main()
{
	int i, j, k, flag = 0;
	int n;
	cout << "请输入二元关系对应方阵(n * n)的行数:\n";
	cin >> n;
	cout << "请输入此方阵:\n";
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
			cin >> a[i][j];
	}
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
		{
			for (k = 0; k < n; k++)
			{
				c[i][j] = c[i][j] + a[i][k] * a[k][j];
			}
		}
	}
	cout << endl;
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
		{
			cout << c[i][j] << " ";
		}
		cout << endl;
	}
	cout << endl;
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
		{
			if (a[i][j] == 0)
			{
				if (c[i][j] != 0)
				{
					cout << "No transitivity!\n";
					return 0;
				} 
			}
		}
	}
	cout << "Transitivity!\n";
	return 0;
}

方法二:中途点判别法

参考网址:http://blog.csdn.net/dancheng1/article/details/52649769?locationNum=2

思路:利用矩阵表示方法,遍历这个矩阵如果遇到一个等于1的位置,记录位置,利用其纵坐标当下一个数的横坐标,在此横坐标下找到是1的位置,记录这个位置,在利用上一个数位置的横坐标和这个数的纵坐标找到一个新的位置,如果这个位置上是1,那么这个数就具有可传递性,然后继续遍历进行这个循环操作,知道检查到所有的数都对上了,这个二元关系才可说具有可传递性,有一个不符的都不是可传递性的二元关系。

代码如下:

#include <iostream>  
using namespace std;  
const int MAXN = 100;  
int A[MAXN][MAXN];  
int main()  
{  
    cout<<"请输入具有二元关系的两个集合的大小:\n";  
    int x , y ;  
    cin>>x>>y;  
    cout<<"请输入这两个集合的二元关系矩阵表示法:\n";  
    for(int i = 0 ; i < x ; i++)  
        for(int j = 0 ; j < y ; j++)  
            cin>>A[i][j];  
    int p = 0 ;  
    for(int i = 0 ; i < x ; i++)  
    {  
        for(int j = 0 ; j < y ; j++)  
        {  
            if( 1 == A[i][j] )  
            {  
                for(int k = 0 ; k < y ; k++)  
                {  
                    if( 1 == A[j][k] && 1 != A[i][k] )  
                    {  
                        p = 1;  
                        break;  
                    }  
                }  
            }  
        }  
    }  
    if(p)  
        cout<<"这个二元关系不具备可传递性!";  
    else  
        cout<<"这个二元关系具备可传递性!";  
}  

猜你喜欢

转载自blog.csdn.net/qq_41705423/article/details/79503938
今日推荐