templates/dijkstra.cpp
compilable
$cat templates/dijkstra
Dijkstra's Algorithm
Shortest path in non-negative weighted graphs using priority queue relaxation in O((V+E) log V).
#dijkstra#shortest-path#priority-queue#graph
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pli = pair<ll, int>;
const ll INF = 1e18;
vector<vector<pair<int, ll>>> adj;
vector<ll> dist;
void dijkstra(int src, int n) {
dist.assign(n + 1, INF);
dist[src] = 0;
priority_queue<pli, vector<pli>, greater<pli>> pq;
pq.push({0, src});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d > dist[u]) continue;
for (auto &[v, w] : adj[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
}26 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Dijkstra's Algorithm
Single-source shortest path for graphs with non-negative edge weights.