Warshall算法求傳遞閉包及具體實現


傳遞閉包

在數學中,在集合 X 上的二元關系 R 的傳遞閉包是包含 R 的 X 上的最小的傳遞關系。

例如,如果 X 是(生或死)人的集合而 R 是關系“為父子”,則 R 的傳遞閉包是關系“x 是 y 的祖先”。再比如,如果 X 是空港的集合而關系 xRy 為“從空港 x 到空港 y 有直航”,則 R 的傳遞閉包是“可能經一次或多次航行從 x 飛到 y”。

Warshall算法

Warshall在1962年提出了一個求關系的傳遞閉包的有效算法。其具體過程如下,設在n個元素的有限集上關系R的關系矩陣為M:
(1)置新矩陣A=M;
(2)置k=1;
(3)對所有i如果A[i,k]=1,則對j=1..n執行:
A[i,j]←A[i,j]∨A[k,j];
(4)k增1;
(5)如果k≤n,則轉到步驟(3),否則停止。
所得的矩陣A即為關系R的傳遞閉包t(R)的關系矩陣。
 要說跟floyd算法有什么關系的話...就是warshall求傳遞閉包他...他沒有記錄路徑長度只是判斷頂點之間是否直接或間接連通(個人理解)
代碼實現:
#include <bits/stdc++.h>
using namespace std;
/* freopen("k.in", "r", stdin);
freopen("k.out", "w", stdout); */
// clock_t c1 = clock();
// std::cerr << "Time:" << clock() - c1 <<"ms" << std::endl;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define de(a) cout << #a << " = " << a << endl
#define rep(i, a, n) for (int i = a; i <= n; i++)
#define per(i, a, n) for (int i = n; i >= a; i--)
#define ls ((x) << 1)
#define rs ((x) << 1 | 1)
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef pair<ll, ll> PLL;
typedef vector<int, int> VII;
#define inf 0x3f3f3f3f
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll MAXN = 1e6 + 7;
const ll MAXM = 1e5 + 7;
const ll MOD = 1e9 + 7;
const double eps = 1e-6;
const double pi = acos(-1.0);
int Mat[20][20]; //
void Print_Mat(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
            cout << Mat[i][j] << " ";
        cout << endl;
    }
    return;
}
void Warshall(int n)
{
    for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (Mat[i][k] && Mat[k][j])
                    Mat[i][j] = 1;
}
int main()
{
    int n;
    cout << "輸入矩陣階數" << endl;
    while (cin >> n)
    {
        memset(Mat, 0, sizeof(Mat));
        cout << "輸入矩陣M:" << endl;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                cin >> Mat[i][j];
        Warshall(n);
        cout << "矩陣M的傳遞閉包為:" << endl;
        Print_Mat(n);
        cout << "輸入矩陣階數" << endl;
    }
    return 0;
}

 

  

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM