Floyd最短路径算法适用于节点(n<200)的图,允许边权值为负。
代码如下:
#include <iostream>
using namespace std;
const int N = 110;
const int INF = 1 << 30;
int g[N][N];
int n, m;void Floyd() {for (int k = 1; k <= n; k++)for (int i = 1; i <= n; i++)if (g[i][k] != INF)for (int j = 1; j <= n; j++) {if (g[i][j] > g[i][k] + g[k][j]) {g[i][j] = g[i][k] + g[k][j];}}}int main() {cin >> n >> m;for (int i = 1; i <= n; i++)for (int j = 1; j <= n; j++)g[i][j] = INF;while (m--) {int a, b, c;cin >> a >> b >> c;g[a][b] = g[b][a] = c;}Floyd();int n1, m1;while (cin >> n1 >> m1, n1, m1)//查询n1点到m1点的最短路径{cout << g[n1][m1] << endl;}return 0;
}