朴素版Dijkstra算法求最短路
思路
与Prim算法思路基本相同,都是选取起点为初始集合,通过遍历其他结点到该集合的最短距离不断更新集合,将更新后的集合重新求最短距离。唯一的区别是:dist距离数组的定义:
(1) Dijkstra算法中 dist[i] 表示结点 i 距离起点1的距离。
(2) prim算法中 dist[i] 表示结点 i 距离动态更新的集合的最短距离。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, INF = 0x3f3f3f3f;
int n,m;
int g[N][N];
bool st[N];
int dist[N]; // 所有结点到起点的距离数组,与prim算法唯一的区别
int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 0; i < n; i ++ )
{
int t = -1;
for (int j = 1; j <= n; j ++ )
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
if (dist[t] == INF) return INF;
st[t] = true;
for (int j = 1; j <= n; j ++)
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
return dist[n];
}
int main()
{
cin >> n >> m;
// 初始化所有结点之间距离为无穷大
memset(g, 0x3f, sizeof g);
while (m -- )
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = min(g[a][b], c);
}
int res = dijkstra();
if (res == INF) cout << -1 << endl;
else cout << res;
return 0;
}