dijsktra算法c++实现
时间: 2023-09-19 09:09:19 浏览: 100
以下是Dijkstra算法的C++实现,假设图的节点为0到n-1:
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
//邻接表存图
struct Edge {
int to, w;
Edge(int _to, int _w) : to(_to), w(_w) {}
};
vector<Edge> graph[100010];
int dist[100010]; //从源点到各个点的最短距离
void dijkstra(int start) {
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
memset(dist, INF, sizeof(dist));
dist[start] = 0;
pq.push(make_pair(0, start));
while (!pq.empty()) {
int u = pq.top().second;
int d = pq.top().first;
pq.pop();
if (d > dist[u]) continue;
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i].to;
int w = graph[u][i].w;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push(make_pair(dist[v], v));
}
}
}
}
int main() {
int n, m, s, u, v, w;
cin >> n >> m >> s;
for (int i = 1; i <= m; i++) {
cin >> u >> v >> w;
graph[u].push_back(Edge(v, w));
}
dijkstra(s);
for (int i = 0; i < n; i++) {
if (dist[i] == INF)
cout << "INF" << endl;
else
cout << dist[i] << endl;
}
return 0;
}
```
其中,使用priority_queue优先队列来维护当前最短的边,使用vis数组来记录当前点是否已经被加入最短路树中。同时,在更新最短距离时,如果新的路径长度还没有之前的路径短,就更新距离并将该点加入队列中。
阅读全文