# 最短路径dijkstra算法与Floyd算法

dijkstra算法与之前的最小生成树的prim算法真的神似，起先都是搜索最小边，然后在更新与初始点距离的数组。

#include<iostream>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAX = 100;
int map[MAX][MAX], dist[MAX], pre[MAX];//点距离数组与前节点数组
bool s[MAX];//判定是否已访问过
int m, n;
void dijkstra(int v0) {
for (int i = 1; i <= n; i++) {
dist[i] = map[v0][i];//当前节点与其他所有点的距离
s[i]=false;//初始化为全未访问过
if (dist[i] == INF) {
pre[i] = -1;
}
else pre[i] = v0;//两点可连接的前节点就是v0
}
s[v0] = true;
dist[v0] = 0;
for (int i = 2; i <= n; i++) {//查找距离最小边
int minor = INF;
int u = v0;
for (int j = 1; j <= n; j++) {
if (!s[j] && dist[j] < minor) {
minor = dist[j];
u = j;
}
}
s[u] = true;
for (int j = 1; j <= n; j++) {//从最小边的点更新之前的与v0的距离
if (!s[j] && dist[u] + map[u][j] < dist[j]) {
dist[j] = dist[u] + map[u][j];
pre[j] = u;//如果有更小边，则说明j的前驱为u
}
}
}
}
int main(void) {
cin >> m >> n;//m为边数，n为顶点数
memset(map, INF, sizeof(map));
for (int i = 0; i < m; i++) {
int a, b, l;
cin >> a >> b >> l;
map[a][b] = l;
}
dijkstra(1);
for (int i = 1; i <= n; i++)//输出v0到其他点的最小距离
cout << dist[i] << " ";
cout << endl;
for (int i = pre[4]; i!=-1; i = pre[i]) {//测试可忽略
cout << i << " ";
}
system("pause");
return 0;
}

ps：由于我这是一个模板，手上也没多少数据可以测试，所以以后用的时候要根据题目再修改。

#include<iostream>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAX = 100;
int map[MAX][MAX], dist[MAX][MAX], pre[MAX][MAX];
int m, n;
void floyd() {
for(int i=1;i<=n;i++)
for (int j = 1; j <= n; j++) {
dist[i][j] = map[i][j];
pre[i][j] = i;
}
for (int i = 1; i <= n; i++) {
for (int k = 1; k <= n; k++) {
for (int j = 1; j <= n; j++) {
if (dist[i][k] != INF&&dist[k][j] != INF&&dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
pre[i][j] = pre[k][j];
}
}
}
}
}

int main(void) {

cin >> m >> n;
memset(map, INF, sizeof(map));
for (int i = 0; i < m; i++) {
int a, b, l;
cin >> a >> b >> l;
map[a][b] = l;
}
floyd();
for (int i = 1; i <= n; i++) {
cout << dist[i][n]<<" ";
}
cout << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cout << pre[i][j]<<" ";
cout << endl;
}
cout << endl;
int i = n;
for (; i != pre[1][i]; i = pre[1][i])//输出路径，可以用栈，这里得到的是逆序路径。
cout << i << " "; cout << i;
system("pause");
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120