用c++代码实现Dijkstra算法,解决如下无向连通有权图的单源最短路径问题,源点为0点,在控制台窗口输出每个点到0点的最短距离和对应的路径。
时间: 2024-03-24 09:37:58 浏览: 56
好的,以下是用C++实现Dijkstra算法的代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
vector<pair<int, int>> G[MAXN];
int dis[MAXN];
bool vis[MAXN];
void Dijkstra(int s) {
memset(dis, INF, sizeof(dis));
memset(vis, false, sizeof(vis));
dis[s] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, s));
while (!pq.empty()) {
int u = pq.top().second; pq.pop();
if (vis[u]) continue;
vis[u] = true;
for (auto &p : G[u]) {
int v = p.first;
int w = p.second;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
pq.push(make_pair(dis[v], v));
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
G[u].push_back(make_pair(v, w));
G[v].push_back(make_pair(u, w));
}
Dijkstra(0);
for (int i = 0; i < n; i++) {
cout << "The shortest distance from 0 to " << i << " is " << dis[i] << ". The path is: ";
vector<int> path;
int cur = i;
path.push_back(cur);
while (cur != 0) {
for (auto &p : G[cur]) {
int v = p.first;
int w = p.second;
if (dis[cur] == dis[v] + w) {
cur = v;
path.push_back(cur);
break;
}
}
}
for (int j = path.size() - 1; j >= 0; j--) {
cout << path[j] << " ";
}
cout << endl;
}
return 0;
}
```
输入格式为:
```
n m
u1 v1 w1
u2 v2 w2
...
um vm wm
```
其中n表示图的节点数,m表示边数,接下来的m行每行输入一条边,u表示起点,v表示终点,w表示边的权值。
输出格式为:
```
The shortest distance from 0 to i is dis_i. The path is: 0 x1 x2 ... xi
```
其中i表示节点编号,dis_i表示节点i到源点0的最短距离,x1, x2, ..., xi表示从源点0到节点i的最短路径上的节点。
阅读全文