洛谷P4779 【模板】单源最短路径(标准版) 题解 Dijkstra+堆优化
题目链接:https://www.luogu.com.cn/problem/P4779
参考博客:https://www.cnblogs.com/-Wind-/p/10164910.html
这里用的是优先队列,时间复杂度 \(O(m \cdot \text{log }m)\) ,实现代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010, maxm = 200020;
const int INF = (1<<29);
struct Edge {
int v, w, nxt;
Edge() {};
Edge(int _v, int _w, int _nxt) { v = _v; w = _w; nxt = _nxt; }
} edge[maxm];
int n, m, s, head[maxn], ecnt;
void init() {
ecnt = 0;
memset(head, -1, sizeof(int)*(n+1));
}
void addedge(int u, int v, int w) {
edge[ecnt] = Edge(v, w, head[u]); head[u] = ecnt ++;
}
struct Node {
int u, dis;
Node() {};
Node(int _u, int _dis) { u = _u; dis = _dis; }
bool operator < (const Node x) const {
return dis > x.dis;
}
};
priority_queue<Node> que;
int dis[maxn];
bool vis[maxn];
void dijkstra_pq() {
memset(dis, -1, sizeof(int)*(n+1));
dis[s] = 0;
que.push(Node(s, 0));
while (!que.empty()) {
Node nd = que.top();
que.pop();
int u = nd.u;
if (vis[u]) continue;
vis[u] = true;
for (int i = head[u]; i != -1; i = edge[i].nxt) {
int v = edge[i].v, w = edge[i].w;
if (dis[v] == -1 || dis[v] > nd.dis + w) {
dis[v] = nd.dis + w;
que.push(Node(v, dis[v]));
}
}
}
}
int main() {
scanf("%d%d%d", &n, &m, &s);
init();
while (m --) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
addedge(u, v, w);
}
dijkstra_pq();
for (int i = 1; i <= n; i ++) printf("%d ", dis[i]);
return 0;
}
应该算最暴力的 “Dijkstra+堆优化”。
关于“Dijkstra+堆优化”的时间复杂度
看用什么堆,手写二叉堆是O(elogv),stl优先队列是O(eloge),斐波那契堆是O(vlogv+e),配对堆复杂度玄学
参考链接:https://tieba.baidu.com/p/5547681010?red_tag=1480858706