Dijkstra算法:
#include<iostream> #include<queue> #include<stack> #include<functional> #define N 1000 #define MAX 1000000 using namespace std; int arcs[N][N]; //邻接矩阵 //Dijkstra算法(稠密) bool visit[N]; //集合 S , visit[i] = true, i 属于集合 S int d[N]; //存放最短路径距离 int parent[N]; //parent[i],路径存在时,存放节点 i 的前驱节点;不存在时,-1 void Dijkstra(int s, int n) { for (int i = 0; i < n; ++i){ //初始化 visit[i] = 0; d[i] = arcs[s][i]; if (d[i] < MAX) parent[i] = s; else parent[i] = -1; } d[s] = 0; visit[s] = true; for (int i = 0; i < n - 1; ++i){ //循环 n-1 次 int min = MAX; int v=0; for (int j = 0; j < n; ++j){ //在集合V-S中,选到 S 距离最小的点 v if (!visit[j] && d[j] < min){ v = j; min = d[j]; } } visit[v] = true; //所选点 v 加入集合 S 中 for (int j = 0; j < n; ++j){ if (!visit[j] && (min + arcs[v][j] < d[j])){ d[j] = min + arcs[v][j]; parent[j] = v; } } } } //Dijkstra算法路径打印 void printPath(int s, int w) { vector<int> v; if (parent[w] == -1){ printf("path is not exit "); return; } do{ v.push_back(w); } while (w = parent[w], w != s); v.push_back(s); int len = v.size(); for (int i = len - 1; i > 0; --i) printf("%d ", v[i]); printf("%d ", v[0]); } int main() { int n; cin >> n; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) cin >> arcs[i][j]; Dijkstra(0, n); for (int i = 0; i < n-1; ++i) cout << d[i] << ' '; cout << d[n - 1] << endl; for (int i = 0; i < n - 1; ++i) cout << parent[i] << ' '; cout << parent[n - 1] << endl; for (int i = 0; i < n; ++i) printPath(0, i); } /* 输入样例: 6 1000000 7 9 1000000 1000000 14 7 1000000 11000000 15 1000000 1000000 9 11000000 1000000 11 1000000 2 1000000 15 11 1000000 6 1000000 1000000 1000000 1000000 6 1000000 9 14 1000000 2 1000000 9 1000000 6 1000000 1000000 10 100000 30 100 1000000 1000000 5 1000000 1000000 1000000 1000000 1000000 1000000 50 1000000 1000000 1000000 1000000 1000000 1000000 1000000 10 1000000 1000000 1000000 20 1000000 60 1000000 1000000 1000000 1000000 1000000 1000000 */