题目思路
数组声明:
dist[i]:从第1个点,到第i个点的最短路径
st[i]:第i个点的更新状态,true已更新,false未更新。
- 初始赋值。dist和g数组均为距离,赋最大值0x3f,表示无穷大,点与点之间不可达;dist[1]=0,第一个点与自身之间无距离。
- dijkstra需要在最外层循环n-1次,目的为将其余的n-1个点的最短距离更新。这里是通过st[j]和t来控制,保证能将n-1个点全部循环一遍。
- 内层循环1。首先判断st[j]是否已经更新过,已更新略过;若未更新,继续找剩余点中dist最小的(找到与第1个点当前dist距离最短的点)。
- 此时经过循环1的t为:状态未更新的点,且与第1个点距离最短的点。
- 内层循环2。不断更新,以t为支点,把剩下的所有点循环一遍,判断是否有通过点t,再走 g[t][j] 更短的路,若有则更新。
C++ 代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 510;
int n, m;
int g[N][N];
int dist[N];
bool st[N];
int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 1; i < n; i++) // 执行 n-1 次
{
int t = -1;
for (int j = 1; j <= n; j++) // 找不在st中,距离最近的点
{
if (!st[j] && (t == -1 || dist[t] > dist[j]))
{
t = j;
}
}
st[t] = true; // 将t放入st中
for (int j = 1; j <= n; j++) // 用t更新所有的点
{
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
}
if (dist[n] == 0x3f3f3f3f)
{
return -1;
}
return dist[n];
}
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
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 t = dijkstra();
cout << t << endl;
return 0;
}