fenwick tree

Dijkstra

Finds shortest distances from a source vertex in a weighted graph. Edge weights must be nonnegative. For an unweighted graph, use breadth-first search.

Implementation

template<class T>
using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;

vector<int> dijkstra(vector<vector<pair<int, int>>> const& G, int source) {
  int N = G.size();

  vector<int> dist(N, -1);
  min_priority_queue<pair<int, int>> Q;
  dist[source] = 0;
  Q.push({dist[source], source});

  while (!Q.empty()) {
    auto [dv, v] = Q.top();
    Q.pop();
    if (dist[v] < dv) continue;

    for (auto [u, w] : G[v]) {
      int du = dv + w;
      if (dist[u] == -1 || dist[u] > du) {
        dist[u] = du;
        Q.push({du, u});
      }
    }
  }

  return dist;
}

Interface

G is a weighted adjacency list with nonnegative weights. Each pair (u, w) in G[v] represents an edge from v to u with weight w. For an undirected edge, include both directions.

Operation Description Time
dijkstra(G, source) Returns the distance from source to each vertex, or -1 for unreachable vertices. O(N+Mlog⁡M){O(N + M \log M)}

NN is the number of vertices and MM is the number of edges.