Floyd算法
定义
求多源带权最小距离(允许有负值,不允许有负环路)(O(V3))
注意
使用memset()函数初始化二维数组时要千万小心:
1.二维整型数组利用memset()函数初始化时,只能初始化为0或者-1,否则二维整型数组的值将为随机数。
2.二维char数组利用memset()函数初始化时不受限制,可初始化为任意字符。
代码
/* ------------------------------------------------- Author: wry date: 2022/3/11 21:00 Description: test ------------------------------------------------- */ #include <bits/stdc++.h> using namespace std; const int MAXN = 100+10; int A[MAXN][MAXN]; int path[MAXN][MAXN]; void Floyd(int n) { for (int k=0;k<n;k++) { for (int i=0;i<n;i++) { if (i==k) { continue; } for (int j=0;j<n;j++) { if (j==k || j==i) { continue; } if (A[i][j]>A[i][k]+A[k][j]) { A[i][j] = A[i][k]+A[k][j]; path[i][j] = k; } } } } } int main() { int n,m; cin >> n>> m; for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { A[i][j] = 1000; } } memset(path,-1,sizeof(path)); for (int i=0;i<m;i++) { int from,to,length; cin >> from >> to >> length; A[from][to] = length; } for (int i=0;i<n;i++) { A[i][i] = 0; } Floyd(n); for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { cout << A[i][j] << " "; } cout << endl; } for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { cout << path[i][j] << " "; } cout << endl; } return 0; }//5 7 //0 2 1 //0 4 10 //1 3 1 //1 4 5 //2 1 1 //2 4 7 //3 4 1