注意这里这段话的理解,我们选择了距离源点最近的点之后,必然不可能再找到比它离源点还近的点了,例如我们找到距离源点最近的点距离是1,那么我们要想通过“中间点”找到比它还小的距离是不可能的,因为单凭这个1就是最小的了,何况我们还要加上另外一段距离
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int e[10][10], dis[10], book[10], i, j, n, m, t1, t2, t3, u, v, minn;
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; i++)//核心代码
{
minn = inf;
for ( j = 1; j <= n; j++)
{
if (book[j] == 0 && dis[j] < minn)
{
minn = dis[j];
u = j;
}
}
book[u] = 1;
for (v = 1; v <= n; v++)
{
if (e[u][v] < inf)
{
dis[v] = min(dis[v], dis[u] + e[u][v]);
}
}
}
for ( i = 1; i <= n; i++)
{
cout << dis[i] << ' ';
}
return 0;
}
以上内容出自啊哈算法