求解代码:
#include <iostream>
using namespace std;
const int inf = 0x7fffffff; //定义一个无限大常量,等效于INT_MAX
int n, e, s;
int dis[101],check[101];
// 辅助数据结构:check数组(检测源点到其他各点是否已是最短路径,初始为0)、distance数组(源点到其余各点的路径,初始为无限大)
// dis数组和check数组设置为至多100个结点(下标0跳过)
int graph[101][101]; //邻接矩阵,表示各顶点连接关系以及各连接边的代价
int main(int argc, char** argv)
{
for (int i = 1; i <= 100; i++) { //dis数组各元素初始化为无限大
dis[i] = inf;
check[i] = false;
}
cin >> e; //e为边数
for (int i = 1; i <= e; i++) {
int a, b, c; //a到b点,代价为c
cin >> a >> b >> c;
graph[a][b] = c;
}
cin >> n >> s; //n为结点个数,s为源点
//××××××××××××××××××××××以上为准备工作××××××××××××××××××××××××××××××××
dis[s] = 0; //源点到源点不需要任何代价
for (int i = 1; i <= n; i++) {
int minVal = inf, minIndex; //minVal表示check[j]==0的结点到源点的最短距离,minIndex为对应点的编号
for (int j = 1; j <= n; j++) {
if (dis[j] < minVal && check[j] == 0) { //呼应minVal与minIndex的定义,同时更新两者的值
minVal = dis[j], minIndex = j;
}
}
check[minIndex] = 1; //记得一定要将check[minIndex]更新为非0
for (int j = 1; j <= n; j++) {
if (graph[minIndex][j] > 0) dis[j] = min(minVal + graph[minIndex][j], dis[j]);
//判断是否更新距离,“绕路”!
}
}
for (int i = 1; i <= n; i++) {
cout << dis[i] << " ";
}
system("pause");
return 0;
}
输出结果: