C/C++ 等价关系判定

推荐阅读:Python基础自学实用笔记(总和篇)-By Ryan_3610

3、题目:等价关系判定

3.1代码

#include <iostream>
#include <stdio.h>
using namespace std;
//等价关系:满足自反对称传递
int main()
{
//输入
    int n,num[20][20];
    cout<<"请输入该关系矩阵阶数:";
    cin>>n;
    for (int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            cin>>num[i][j];
    }
//自反判断
    for(int i = 0;i<n;i++)
    {
        if(num[i][i] != 1)
        {
            cout<<"非等价关系"<<endl;
            return 0;
        }
    }
//对称判断
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
        {
            if (i != j)
            {
                if(num[i][j] != num[j][i])
                {
                    cout<<"非等价关系"<<endl;
                    return 0;
                }
            }
        }
//可传递判断(算法)
    int num0[20][20];
    //矩阵相乘
    int temp=0;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            temp = 0;
            for (int m=0;m<n;m++)
                temp += num[i][m]*num[m][j];
            num0[i][j] = temp;
        }
    }

    //子集判断
    for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			if (num[i][j] == 0)
			{
				if (num0[i][j] != 0)
				{
					cout << "非等价关系"<<endl;
					return 0;
				}
			}
		}
	}
//最后结果
    cout<<"是等价关系"<<endl;
    return 0;
}

3.2测试

5
1 1 0 0 0
1 1 1 0 1
0 1 1 1 0
0 0 1 1 1
0 1 0 1 1

5
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

3.3结果

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45879055/article/details/106784094