Dijkstra算法
作者:
Oct_9
,
2024-04-22 13:00:22
,
所有人可见
,
阅读 11
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 510;
int g[N][N];
int n, m;
int dist[N];
bool st[N];
int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 0; i < n; i ++)
{
int t = -1;
for (int i = 1; i <= n; i ++)
{
if (!st[i] && (t == -1 || dist[i] < dist[t]))
t = i;
}
st[t] = true;
for (int i = 1; i <= n; i ++)
dist[i] = min(dist[i], dist[t] + g[t][i]);
}
return dist[n];
}
int main()
{
scanf("%d%d", &n, &m);
memset(g, 0x3f, sizeof g);
while (m --)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
g[a][b] = min(g[a][b], c);
}
int t = dijkstra();
if (t == 0x3f3f3f3f) printf("-1");
else printf("%d\n", t);
return 0;
}