1. 程式人生 > >【離散數學】Warshall演算法實現 傳遞閉包對應矩陣

【離散數學】Warshall演算法實現 傳遞閉包對應矩陣

測試樣例,資料拿離散書上Page 124頁測的:

/*

7
1 1 0 0 0 0 0 
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

*/

程式碼:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;

const int len = 1000 + 100;
int M[len][len];   //原方陣
int A[len][len];   //置新後方陣
int n, i, j;       //n表示方陣行數

void Wareshall()
{
    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= n; j++)
        {
            if(A[j][i] == 1)
            {
                for(int k = 1; k <= n; k++)
                {
                    A[j][k] = A[j][k] + A[i][k];
                    if(A[j][k] >= 1)
                    {
                        A[j][k] =  1;
                    }
                }
            }
        }
    }
}

int main()
{
    freopen("datain.txt","r",stdin);
    cout << "輸入原方陣行數:" << endl;
    cin >> n;
    cout << endl;
    cout << "輸入原關係矩陣(方陣):";
    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= n; j++)
        {
            cin >> M[i][j];
            A[i][j] = M[i][j];
        }
    }
    Wareshall();
    cout << "輸出傳遞閉包對應關係矩陣:" << endl;
    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= n; j++)
        {
            cout << A[i][j] <<"  ";
        }
        cout << endl;
    }

    return 0;
}