$cat templates/dijkstra
Dijkstra's Algorithm
Shortest path from single source (non-negative weights)
#shortest-path#graph#dijkstra
$cat code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
using ll = long long;
using pll = pair<ll, int>;
const ll INF = 1e18;
vector<ll> dijkstra(int start, const vector<vector<pair<int, ll>>> &g) {
int n = g.size();
vector<ll> dist(n, INF);
priority_queue<pll, vector<pll>, greater<>> pq;
dist[start] = 0;
pq.emplace(0, start);
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d != dist[u]) continue;
for (auto &[v, w] : g[u])
if (dist[v] > dist[u] + w)
pq.emplace(dist[v] = dist[u] + w, v);
}
return dist;
}19 linesutf-8
$cat notes.txt
Use priority queue for . Does not work with negative weights.