堆优化版dijkstra算法c++
时间: 2023-11-12 08:59:48 浏览: 128
好的,以下是堆优化版Dijkstra算法的C++代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1005;
struct Edge {
int to, w;
Edge(int to, int w) : to(to), w(w) {}
};
vector<Edge> G[MAXN];
int d[MAXN];
void dijkstra(int s) {
memset(d, INF, sizeof(d));
d[s] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> que;
que.push(make_pair(0, s));
while (!que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (d[v] < p.first) continue;
for (int i = 0; i < G[v].size(); i++) {
Edge e = G[v][i];
if (d[e.to] > d[v] + e.w) {
d[e.to] = d[v] + e.w;
que.push(make_pair(d[e.to], e.to));
}
}
}
}
int main() {
int n, m, s;
cin >> n >> m >> s;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
G[u].push_back(Edge(v, w));
}
dijkstra(s);
for (int i = 1; i <= n; i++) {
if (d[i] == INF) cout << "INF" << endl;
else cout << d[i] << endl;
}
return 0;
}
```
堆优化版Dijkstra算法的时间复杂度为O((E+V)logV),其中E为边数,V为顶点数。
阅读全文