I've implemented the Dijkstra Algorithm to obtain the minimum paths between a source node and every other.
#include <bits/stdc++.h>
typedef std::vector<std::list<int>> AdjacencyList;
typedef std::vector<std::vector<int>> Weights;
std::vector<int> dijkstra(AdjacencyList &adj, Weights weights, int src) {
int n = adj.size();
std::vector<int> prev(n, -1);
std::vector<int> dist (n, INT_MAX);
std::vector<bool> visited(n, false);
auto comp = [&dist](const int& lhs, const int& rhs) -> bool { return dist[lhs] > dist[rhs]; };
std::priority_queue<int, std::vector<int>, decltype(comp)> candidates(comp);
candidates.push(src);
dist[src] = 0;
for (int j = 0; j < n - 1; ++j) {
int next = candidates.top();
candidates.pop();
visited[next] = true;
for(std::list<int>::const_iterator it = adj[next].begin(); it != adj[next].end(); it++) {
int neighbor = *it;
if (!visited[neighbor] && (dist[next] + weights[next][neighbor] < dist[neighbor])) {
dist[neighbor] = dist[next] + weights[next][neighbor];
prev[neighbor] = next;
candidates.push(neighbor);
}
}
}
return prev;
}
I wrote this code to practice but also to be used at competition contests. So, i want this to be simple, clear and efficient at the same time (without losing so much readability). Any advices?