
Dijkstra's Algorithm and Its Implementation with STL
Suppose there is a country with a set of cities (let's denote this set as ) and a set of roads connecting pairs of cities (let's denote them as ). Not every pair of cities is necessarily connected by a road. Sometimes, to get from one city to another, you have to pass through several transit cities. Each road has a length. Country has a capital city . We need to find the shortest paths from the capital to all other cities.
Here is the mathematical formulation of this problem:
Let G = (V, E) be a directed graph in which every edge is labeled with a non-negative number (the edge weight). Mark some vertex and call it the source. Find the shortest paths from the source to all other vertices of the graph .
This problem is known as the single-source shortest paths problem.
Any part of a shortest path is itself a shortest path. This allows us to apply dynamic programming to the problem.
Dynamic programming is applied to problems that belong to some family of similar problems, where some problems in the family are simple and have obvious solutions, and where solutions to new problems can be built from solutions already found. In our case, the problem “find the shortest path from to ” is one of the problems of the form “find the shortest path from to ”. One of these problems has an obvious solution: “find the shortest path from to ” – you don't need to go anywhere, the shortest path has length . What remains is to find a way to expand the set of solved problems of this form step by step.
Problems solved by dynamic programming are said to have optimal substructure and to break down into many overlapping subproblems. Optimal substructure means that optimal solutions of smaller subproblems can be used to solve the whole problem. As a rule, solving such problems starts with choosing a set of parameters over which the computation runs. The relationship between parameters and subproblems is expressed by recurrence relations. While processing subproblems, their intermediate results are memoized (usually in arrays).
Our shortest paths problem has the required optimal substructure property:
Lemma. Let G = (V, E) be a weighted directed graph with weight function : E → R^{+}. If p = (v_1, v_2, …, v_k) is a shortest path from v_1 to v_k and 1 ≤ i ≤ j ≤ k, then p_{ij} = (v_i, v_{i+1}, …, v_j) is a shortest path from v_i to v_j.
Let d(u, v) denote the length of the shortest path between vertices and . The weight of the edge between vertices and is denoted w(x, y).
Corollary. Consider a shortest path from to . Let u → v be the last edge of this path. Then d(s, v) = d(s, u) + w(u, v).
Lemma. Let G = (V, E) be a weighted directed graph with weight function : E → R^{+}. Let s \in V. Then for every edge (u, v) \in E the following inequality holds:
To solve the single-source shortest path problem, we will use Dijkstra's greedy algorithm. The greedy choice is justified here, since a sequence of locally optimal choices yields a globally optimal solution.
Dijkstra's algorithm builds a set of vertices whose shortest paths from the source are already known. At each step, the vertex whose distance from the source is no greater than that of any other vertex is added to . This way of adding vertex is exactly what characterizes the greedy choice. Once is added to , the shortest distance from the source to will never improve, so we set used[v] = 1. Since edge weights are non-negative, the shortest path from the source to any vertex in passes only through vertices in . We will call such a path special. At each step the algorithm uses an array d, which stores the lengths of the shortest special paths for every vertex. Once contains all vertices of the graph (special paths have been found for all vertices), the array d contains the lengths of the shortest paths from the source to every vertex.

Input. The first line contains the number of vertices in the graph and the number of the source vertex . Each following line describes a directed edge of the graph and contains the numbers of the vertices it connects, followed by its weight. The vertices are numbered from to .
Output. For each vertex of the graph, print the line: From source s to destination v distance is dist
Here dist is the shortest distance from the source to vertex . Print the lines in increasing order of vertex numbers .
6 4
1 2 9
1 5 2
2 3 1
2 4 8
3 6 3
4 1 5
4 3 16
5 4 4
5 6 7
6 4 5From source 4 to destination 1 distance is 5
From source 4 to destination 2 distance is 14
From source 4 to destination 3 distance is 15
From source 4 to destination 4 distance is 0
From source 4 to destination 5 distance is 7
From source 4 to destination 6 distance is 14The graph from the sample test looks like this:

Implementing Dijkstra's Algorithm with Arrays
Assume the vertices of graph are labeled with integers, one of which is the source. The matrix element m[i][j] holds the weight of edge . If edge does not exist, m[i][j] is set to the maximum value. We set used[i] = 1 once vertex has been added to . The vertex numbered source is the source.
#include<stdio.h>
#include<memory.h>
#define MAX 100
#define INF 2100000000
int i,j,n,source;
int b,e,dist,v;
int m[MAX][MAX],used[MAX],d[MAX];
// Initialize the arrays used by the algorithm.
void Init(void) {
memset(m,63,sizeof(m));
memset(used,0,sizeof(used));
memset(d,63,sizeof(d));
d[source] = 0;
}
// Relax edge (i, j).
void Relax(int i, int j) {
if (d[j] > d[i] + m[i][j]) d[j] = d[i] + m[i][j];
}
// Find the unused vertex with the smallest distance from the source (value d[i]).
int Find_Min(void) {
int i,v = -1,min = INF / 2;
for(i=1;i<=n;i++)
if (!used[i] && d[i] < min) min = d[i], v = i;
return v;
}
int main(void) { Initialize the arrays and read the input graph. Initially, the distances from vertex source to all other vertices are set to plus infinity, while d[source] = 0, since the distance from source to itself is zero. Initially, the set consists of the single vertex source.
scanf("%d %d", &n, &source);
Init();
while(scanf("%d %d %d", &b, &e, &dist) == 3)
m[b][e] = dist;Run the loop n - 1 times. At each iteration, the vertex whose distance from the source is no greater than that of any other vertex not yet in is added to . Relax all edges going out of . The shortest distance from the source to will never improve, so we add to and set used[v] = 1.
for (i = 1; i < n; i++) {
v = Find_Min();
if (v == -1) break;
for (j = 1; j <= n; j++)
if (!used[j])
Relax(v,j);
used[v] = 1;
}Print the result. Cell d[i] holds the shortest distance from vertex source to i.
for (i = 1; i <= n; i++)
printf("From source %d to destination %d distance is %d\n", source, i, d[i]);
return 0;
}Example. Consider the graph from the sample test. Vertex 4 is the source. Initialize S = \{\}. For every , set d[k] to the maximum natural number, while d[4] = 0, since the distance from a vertex to itself is .
On the first iteration, find the smallest value among d[i], where is a vertex not yet in : min(d[1], d[2], d[3], d[4], d[5], d[6]) = d[4] = 0. Vertex is the first to be added to . Recompute d[i] for all i \in V \ S = {1, 2, 3, 5, 6}:
d[1] = min(d[1], d[4] + m[4][1]) = min(MAX, 0 + 5) = 5;
d[2] = min(d[2], d[4] + m[4][2]) = min(MAX, 0 + MAX) = MAX;
d[3] = min(d[3], d[4] + m[4][3]) = min(MAX, 0 + 16) = 16;
d[5] = min(d[5], d[4] + m[4][5]) = min(MAX, 0 + MAX) = MAX;
d[6] = min(d[6], d[4] + m[4][6]) = min(MAX, 0 + MAX) = MAX;Now the second iteration. Find the minimum among d[i], where і \in S: min(d[1], d[2], d[3], d[5], d[6]) = d[1] = 5. Vertex is the second to be added to , so S = \{1, 4\}. Recompute d[i] for all i \in V \ S = \{2, 3, 5, 6\}:
d[2] = min(d[2], d[1] + m[1][2]) = min(MAX, 5 + 9) = 14;
d[3] = min(d[3], d[1] + m[1][3]) = min(16, 5 + MAX) = 16;
d[5] = min(d[5], d[1] + m[1][5]) = min(MAX, 5 + 2) = 7;
d[6] = min(d[6], d[1] + m[1][6]) = min(MAX, 5 + MAX ) = MAX;The results of all iterations are shown in the table. The vertex selected and added to at each step is highlighted and underlined. Values d[i] for which i \in S are shown in italics.
The Iterative Process of Dijkstra's Algorithm
Next, let's look at implementations of Dijkstra's algorithm using various containers and functions from the STL template library.
STL (Standard Template Library) is a set of function and class templates in C++ that includes various data containers (list, queue, set, map, hash table, priority queue) and basic algorithms (sorting, searching). The history and core concepts of the library can be found, for example, on Wikipedia. A detailed description of STL is available at http://www.sgi.com/tech/stl/.
Implementing Dijkstra's Algorithm with a Priority Queue
Let's implement Dijkstra's algorithm with a priority queue. This data structure is provided by STL as priority_queue. It stores (key, value) pairs and performs two operations quickly:
inserting an element with a given priority;
extracting the element with the highest priority;
Declare a priority queue pq whose elements are pairs (distance, node), where distance is the distance from the source to vertex node. As elements are inserted, the pair (distance, node) with the smallest distance is always at the head of the queue. So the number of the unused vertex closest to the source is available as pq.top().second.
#include <cstdio>
#include <queue>
#include <vector>
#define MAX 10001
using namespace std;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // (distance,node)
vector<vector<pair<int, int>>> g(MAX); // g[a] = (b, weight)
vector<int> dist(MAX, 0x3FFFFFFF);
int n,src;
int main(void) {
int i,a,b,d;
scanf("%d %d", &n, &src);
while (scanf("%d %d %d", &a, &b, &d) == 3)
g[a].push_back(make_pair(b, d));
pq.push(make_pair(0,src)); dist[src] = 0;
while (!pq.empty()) {
pair<int, int> s = pq.top(); pq.pop();
int v = s.second;
if (s.first > dist[v]) continue;
for (auto &e : g[v])
if (dist[e.first] > dist[v] + e.second) {
dist[e.first] = dist[v] + e.second;
pq.push(make_pair(dist[e.first], e.first));
}
}
for (i = 1; i <= n; i++)
printf("From source %d to destination %d distance is %d\n",src, i, dist[i]);
return 0;
}Implementing Dijkstra's Algorithm with a Set
Let's simulate a priority queue with a set set<pair<int, int>> s. Its elements are pairs whose second element is a vertex number and whose first element is the current best distance from the source to vertex (the value d[i]). The advantage of storing data this way is that the elements of are always sorted by the first component of the pair. So the pair with the vertex to be added to next is at the front of and is available as s.begin().
#include<cstdio>
#include<set>
#include<cstring>
#define MAX 1001
#define INF 0x3F3F3F3F
using namespace std;
typedef pair<int, int> ii;
int i, v, n, dist, source, b, e;
int m[MAX][MAX], d[MAX];
set<ii> s;
int main(void) {
scanf("%d %d", &n, &source);
memset(m, 63, sizeof(m));
while(scanf("%d %d %d", &b, &e, &dist) == 3)
m[b][e] = dist;
memset(d, 0x3F, sizeof(d));
d[source] = 0;
s.insert(ii(0,source));The body of the while loop runs n times (n is the number of vertices in the graph). At each iteration, exactly one vertex is added to the set S and removed from further consideration. On the last, n-th iteration, no edge is relaxed, and the entry for the last vertex is removed from s.
while (!s.empty()) {
ii top = *s.begin();
s.erase(s.begin());
v = top.second;Vertex v is added to at the current step. Relax the edges going out of v. If edge is relaxed, remove the pair (d[i], i) from s and insert (d[v] + m[v][i], i).
for (i = 1; i <= n; i++) {
if (d[i] > d[v] + m[v][i]) {
if (d[i] != INF)
s.erase(s.find(ii(d[i],i)));
d[i] = d[v] + m[v][i];
s.insert(ii(d[i],i));
}
}
}
for (i = 1; i <= n; i++)
printf("From source %d to destination %d distance is %d\n",source, i, d[i]);
return 0;
}Implementing Dijkstra's Algorithm with a Heap
As is well known, a priority queue can be implemented with a heap. Instead of declaring a priority queue directly, we will use a vector of pairs pq, and when inserting/extracting elements we will use the STL functions pop_heap and push_heap, which maintain the heap property. The heap property is maintained over all elements of pq.
#include<cstdio>
#include<vector>
#include<algorithm>
#include<functional>
#define MAX 10001
using namespace std;
vector<pair<int, int>> pq; // (distance,node)
vector<vector<pair<int, int>>> g(MAX); // g[a] = (b, weight)
vector<int> dist(MAX,0x3FFFFFFF);
int n, src;
int main(void) {
int i, a, b, d;
scanf("%d %d", &n, &src);
while (scanf("%d %d %d", &a, &b, &d) == 3)
g[a].push_back(make_pair(b, d));
pq.push_back(make_pair(0,src));
dist[src] = 0;
while (!pq.empty()) {
pop_heap(pq.begin(), pq.end(), greater<pair<int, int>>());
pair<int, int> s = pq.back();
pq.pop_back();
int v = s.second;
if (s.first > dist[v]) continue;
for (auto &e : g[v])
if (dist[e.first] > dist[v] + e.second) {
dist[e.first] = dist[v] + e.second;
pq.push_back(make_pair(dist[e.first], e.first));
push_heap(pq.begin(), pq.end(), greater<pair<int, int>>());
}
}
for (i = 1; i <= n; i++)
printf("From source %d to destination %d distance is %d\n", src, i, dist[i]);
return 0;
}Running Time of Dijkstra's Algorithm
With arrays, the shortest path algorithm performs n - 1 iterations, and in each of them finding vertex and relaxing edges takes time. So the total running time is O(n^2).
For shortest paths on sparse graphs, it is better to use a priority queue. The running time is then O((|V| + |E|) lg|V|) = O(|E| lg|V|), where |V| = n is the number of vertices and is the number of edges in the graph.
Shortest path problems are quite common in programming competitions. For example, the following problems require implementing Dijkstra's algorithm:
Tianjin University (TJU): 2134 (106 miles to Chicago), 2819 (Travel), 2870 (The K-th City).
TopCoder: SRM 241 (AirTravel).
References
Cormen T., Leiserson C., Rivest R., Stein C. "Introduction to Algorithms" (Russian edition: "Алгоритмы: построение и анализ"), Moscow, Saint Petersburg, Kyiv, 2005 – 1292 p.
Vinokurov N.A., Vorozhtsov A.V. "Practice and Theory of Programming", Book 2. Moscow: Fizmatkniga, 2008 – 288 p.
Article "Binary Heap", Potentsial magazine No. 7, 2007.
Комментарийлер