ja / en
Overview

Dijkstra

2024/07/30
1 min read

Purpose

Finds the shortest distance from a specified vertex to all other vertices. Assumes no negative edges.

Time Complexity

O(ElogV)O(|E|\log|V|)

Depends

Usage

Declaration

auto res = dijkstra(g,s);

Get the shortest distance from vertex s to vertex i using res[i].

Implementation

vector<int> dijkstra(DirectedGraph &_g,int s) {
vector<int> d(_g.n, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> que;
d[s] = 0;
que.push(make_pair(0, s));
while (!que.empty()) {
pair<int, int> p = que.top();
que.pop();
int v = p.second;
if (d[v] < p.first)
continue;
for (auto e : _g.g[v]) {
if (d[e.to] > d[v] + e.cost) {
d[e.to] = d[v] + e.cost;
que.push(make_pair(d[e.to], e.to));
}
}
}
return d;
}