Files
python/C++课程/待整理知识/最短路径/Dijkstra.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

65 lines
1019 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<iostream>
using namespace std;
int main()
{
// dev代码拷贝中文乱码的解决方案
// .cpp文件用记事本打开,再拷贝
//黄海注释
int e[10][10], dis[10], book[10], i, j, n, m, t1, t2, t3, u, v, min;
int inf = 99999999;
cin >> n >> m;
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
{
if (i == j) {
e[i][j] = 0;
}
else {
e[i][j] = inf;
}
}
for (i = 1; i <= m; i++)
{
cin >> t1 >> t2 >> t3;
e[t1][t2] = t3;
}
for (i = 1; i <= n; i++)
{
dis[i] = e[1][i];
}
for (i = 1; i <= n; i++)
{
book[i] = 0;
}
book[1] = 1;
for (i = 1; i <= n - 1; i++)
{
min = inf;
for (j = 1; j <= n; j++)
{
if (book[j] == 0 && dis[j] < min)
{
min = dis[j];
u = j;
}
}
book[u] = 1;
for (v = 1; v <= n; v++)
{
if (e[u][v] < inf)
{
if (dis[v] > dis[u] + e[u][v])
{
dis[v] = dis[u] + e[u][v];
}
}
}
}
for (i = 1; i <= n; i++)
cout << dis[i] << " ";
return 0;
}