AcWing 849. Dijkstra求最短路 I
原题链接
简单
作者:
陆离
,
2021-04-06 23:47:49
,
所有人可见
,
阅读 477
步骤
- 初始化dist[], dist[1] = 0, 其余设置为∞
- n次迭代dist
- t=-1时,t=j=1, 更新n个点的dist[]
- 求出比t=1距离更小的点,即离起点最近的点
- 用4中的点去更新dist[]
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510;
int dist[N];
int st[N];
int n, m;
int g[N][N];
int dijkstra()
{
// 初始化dist[]
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 0; i < n; i ++)
{
int t = -1; // A
for (int j = 1; j <= n; j ++)
{
if (!st[j] && (t == -1 || dist[j] < dist[t]))
t = j;
}
st[t] = true;
for(int j = 1; j <= n; j ++)
{
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
// int a, b, c;
cin >> n >> m;
memset(g, 0x3f, sizeof g);
for (int i = 1; i <= m; i ++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
// add(a, b, c);
g[a][b] = min(g[a][b], c);
}
cout << dijkstra() << endl;
return 0;
}