Dijkstra算法是解决单源的最短路径的算法。该算法对于负值的图无能为力。
所谓单源,就是起点已确定,但是终点不同,不同点到起点的最短路径。
Dijkstra算法的大体思路是先找到与起点A相邻的点且距离起点最近的点B,AB的距离为B到A距离最近的点。在从B相邻的点和之前的点中比较找到距离A最近的点C。
如此循环往复,确定每个点到点A的距离是最短的。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MAXN = 10000;
int maps[MAXN+3][MAXN+3];//点到点的距离
int dist[MAXN+3];//所求点到源点的距离
int pre[MAXN+3];//键对应的值,该点的上一个点为值
bool v[MAXN+3];//标记带点是否被使用
void Dijstra(int n, int s) {
for(int i = 1; i <= n; i++) {//初始化
v[i] = false;
if(i != s) {
dist[i] = maps[s][i];
pre[i] = s;//i的上一个点为s
}
}
dist[s] = 0; v[s] = true;//s点到s点距离为零,s点以用过
for(int i = 1; i <= n - 1; i++) {
int minn = INF;
int k = 0;
for(int j = 1; j <= n; j++) {//找出哪个点到源点的距离最小
if(!v[j] && dist[j] < minn) {
minn = dist[j], k =j;
}
}
if(!k) return ;
v[k] = true;
for(int j = 1; j <= n; j++) {//刷新与k点相邻的点到源点的距离
if(!v[j] && maps[k][j]!=INF && dist[j] > dist[k] + maps[k][j]) {
dist[j] = dist[k] + maps[k][j];
pre[j] = k;
}
}
}
}
void init(int m) {//初始化
for(int i = 0; i < m; i++) {
for(int j = 0; j < m; j++) {
maps[i][j] = INF;
}
pre[i] = i;
}
}
int main() {
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n, m, x, y, w;
while(cin >> n >> m) {
init(m);
for(int i = 0; i < m; i++) {
cin >> x >> y >> w;
maps[x][y] = maps[y][x] = w;
}
Dijstra(n,1);
for(int i = 1; i <= n; i++)
cout << dist[i] << endl;
}
return 0;
}