dijkstra算法c++
时间: 2023-10-18 22:22:46 浏览: 63
以下是Dijkstra算法的C++代码实现:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
typedef pair<int, int> pii;
const int MAXN = 100005;
vector<pii> graph[MAXN];
int dist[MAXN];
void dijkstra(int start) {
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push(make_pair(0, start));
dist[start] = 0;
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i].first;
int w = graph[u][i].second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push(make_pair(dist[v], v));
}
}
}
}
int main() {
int n, m, s;
cin >> n >> m >> s;
for (int i = 1; i <= n; i++) {
dist[i] = INT_MAX;
}
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back(make_pair(v, w));
}
dijkstra(s);
for (int i = 1; i <= n; i++) {
if (dist[i] == INT_MAX) {
cout << "INF" << endl;
} else {
cout << dist[i] << endl;
}
}
return 0;
}
```
输入格式为:第一行是节点数n,边数m,源点s;接下来m行是每条边的起点、终点和权值。
输出格式为:从源点s到每个节点的最短路,若不连通则输出”INF”。
该实现使用了优先队列,时间复杂度为O(mlogn)。
阅读全文