44 const int INF = std::numeric_limits<int>::max();
53 void dijkstra(
const std::vector<std::vector<Edge>> &graph,
55 std::vector<int> &distances,
56 std::vector<int> &parents) {
58 distances.assign(n,
INF);
59 parents.assign(n, -1);
61 distances[source] = 0;
62 std::priority_queue<std::pair<int, int>,
63 std::vector<std::pair<int, int>>,
64 std::greater<std::pair<int, int>>>
66 pq.push(std::make_pair(0, source));
69 int current = pq.top().second;
70 int distance = pq.top().first;
73 if (distance > distances[current])
76 for (
const Edge &edge : graph[current]) {
77 int neighbor = edge.to;
78 int new_distance = distance + edge.weight;
80 if (new_distance < distances[neighbor]) {
81 distances[neighbor] = new_distance;
82 parents[neighbor] = current;
83 pq.push(std::make_pair(new_distance, neighbor));
91 std::vector<std::vector<Edge>> graph(n);
93 graph[0].push_back({1, 2});
94 graph[0].push_back({2, 5});
95 graph[1].push_back({2, 1});
96 graph[1].push_back({3, 3});
97 graph[2].push_back({3, 1});
100 std::vector<int> distances, parents;
101 dijkstra(graph, source, distances, parents);
104 std::cout <<
"Shortest distance from " << source <<
" to " << destination
105 <<
": " << distances[destination] << std::endl;
106 std::cout <<
"Shortest path: ";
107 for (
int node = destination; node != -1; node = parents[node])
108 std::cout << node <<
" ";
109 std::cout << std::endl;
void dijkstra(const std::vector< std::vector< Edge >> &graph, int source, std::vector< int > &distances, std::vector< int > &parents)