求单源最短路使用Dijkstra算法,堆优化版本时间复杂度在O(nlogn)
题目链接:https://www.luogu.com.cn/record/153709192(注意此图是有向图)
使用优先队列使每次出队的都是距离最小值对应点
#include <iostream>
#include <queue>
#include <cstring>
#include <vector>
using namespace std;
const int N = 1e6 + 10, M = 1e9 + 10;
int e[N * 2], ne[N * 2], h[N];
long long w[2 * N], idx;
long long dist[N];
int n, m, s;
bool st[N];
typedef pair<int, int> pii;
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c,
h[a] = idx++;
}
void dijkstra() {
memset(dist, M, sizeof dist);
dist[s] = 0;
priority_queue<pii, vector<pii>, greater<pii>> heap;
heap.push({ 0, s });
while (heap.size()) {
pii t = heap.top();
heap.pop();
int ver = t.second, distance = t.first;
if (st[ver])
continue;
st[ver] = true;
for (int i = h[ver]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > distance + w[i]) {
dist[j] = distance + w[i];
heap.push({dist[j],j});
}
}
}
}
int main() {
cin >> n >> m >> s;
int a, b, c;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i++) {
cin >> a >> b >> c;
add(a, b, c);
}
dijkstra();
for (int i = 1; i <= n; i++)
cout << dist[i] << ' ';
return 0;
}