|
| 1 | +<!--?title Dijkstra on sparse graphs --> |
| 2 | +# Dijkstra on sparse graphs |
| 3 | + |
| 4 | +For the statement of the problem, the algorithm with implementation and proof can be found on the article [Dijkstra's algorithm](./graph/dijkstra.html). |
| 5 | + |
| 6 | +## Algorithm |
| 7 | + |
| 8 | +We recall in the derivation of the complexity of Dijkstra's algorithm we used two factors: |
| 9 | +the time of finding the unmarked vertex with the smallest distance $d[v]$, and the time of the relaxation, i.e. the time of changing the values $d[\text{to}]$. |
| 10 | + |
| 11 | +In the simplest implementation these operations require $O(n)$ and $O(1)$ time. |
| 12 | +Therefore, since we perform the first operation $O(n)$ times, and the second one $O(m)$ times, we obtained the complexity $O(n^2 m)$. |
| 13 | + |
| 14 | +It is clear, that this complexity is optimal for a dense graph, i.e. when $m \approx n^2$. |
| 15 | +However in sparse graphs, when $m$ is much smaller than the maximal number of edges $n^2$, the complexity gets less optimal because of the first term. |
| 16 | +Thus it is necessary to improve the execution time of the first operation (and of course without greatly affecting the second operation by much). |
| 17 | + |
| 18 | +To accomplish that we can use a variation of multiple auxiliary data structures. |
| 19 | +The most efficient is the **Fibonacci heap**, which allows the first operation to run in $O(\log n)$, and the second operation in $O(1)$. |
| 20 | +Therefore we will get the complexity $O(n \log n + m)$ for Dijkstra's algorithm, which is also the theoretical minimum for the shortest path search problem. |
| 21 | +Therefore this algorithm works optimal, and Fibonacci heaps are the optimal data structure. |
| 22 | +There doesn't exist any data structure, that can perform both operations in $O(1)$, because this would also allow to sort a list of random numbers in linear time, which is impossible. |
| 23 | +Interestingly there exists an algorithm by Thorup that finds the shortest path in $O(m)$ time, however only works for integer weights, and uses a completely different idea. |
| 24 | +So this doesn't lead to any contradictions. |
| 25 | +Fibonacci heaps provide the optimal complexity for this task. |
| 26 | +However they are quite complex to implement, and also have a quite large hidden constant. |
| 27 | + |
| 28 | +As a compromise you can use data structures, that perform both types of operations (extracting a minimum and updating an item) in $O(\log n)$. |
| 29 | +Then the complexity of Dijkstra's algorithm is $O(n \log m + m \log n) = O(m \log n)$. |
| 30 | + |
| 31 | +C++ provides two such data structures: `set` and `priority_queue`. |
| 32 | +The first is based on red-black trees, and the second one on heaps. |
| 33 | +Therefore `priority_queue` has a smaller constant hidden constant, but also has a drawback: |
| 34 | +it doesn't support the operation of removing an element. |
| 35 | +Because of this we need to do a "workaround", that actually leads to a slightly worse factor $\log m$ instead of $\log n$ (although in terms of complexity they are identical). |
| 36 | + |
| 37 | +## Implementation |
| 38 | + |
| 39 | +### set |
| 40 | + |
| 41 | +Let us start with the container `set`. |
| 42 | +Since we need to store vertices ordered by their values $d[]$, it is convenient to store actual pairs: the distance and the index of the vertex. |
| 43 | +As a result in a `set` pairs are automatically sorted by their distances. |
| 44 | + |
| 45 | +```cpp dijkstra_sparse_set |
| 46 | +const int INF = 1000000000; |
| 47 | +vector<vector<pair<int, int>>> adj; |
| 48 | + |
| 49 | +void dijkstra(int s, vector<int> & d, vector<int> & p) { |
| 50 | + int n = adj.size(); |
| 51 | + d.assign(n, INF); |
| 52 | + p.assign(n, -1); |
| 53 | + |
| 54 | + d[s] = 0; |
| 55 | + set<pair<int, int>> q; |
| 56 | + q.insert({0, s}); |
| 57 | + while (!q.empty()) { |
| 58 | + int v = q.begin()->second; |
| 59 | + q.erase(q.begin()); |
| 60 | + |
| 61 | + for (auto edge : adj[v]) { |
| 62 | + int to = edge.first; |
| 63 | + int len = edge.second; |
| 64 | + |
| 65 | + if (d[v] + len < d[to]) { |
| 66 | + q.erase({d[to], to}); |
| 67 | + d[to] = d[v] + len; |
| 68 | + p[to] = v; |
| 69 | + q.insert({d[to], to}); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | +``` |
| 75 | +
|
| 76 | +We don't need the array $u[]$ from the normal Dijkstra's algorithm implementation any more. |
| 77 | +We will use the `set` to store that information, and also find the vertex with the shortest distance with it. |
| 78 | +It kinda acts like a queue. |
| 79 | +The main loops executes until there are no more vertices in the set/queue. |
| 80 | +A vertex with the smallest distance gets extracted, and for each successful relaxation we first remove the old pair, and then after the relaxation add the new pair into the queue. |
| 81 | +
|
| 82 | +### priority_queue |
| 83 | +
|
| 84 | +The main difference to the implementation with `set` is that we cannot remove elements from the `priority_queue` (although heaps can support that operation in theory). |
| 85 | +Therefore we have to cheat a little bit. |
| 86 | +We simply don't delete the old pair from the queue. |
| 87 | +As a result a vertex can appear multiple times with different distance in the queue at the same time. |
| 88 | +Among these pairs we are only interested in the pairs where the first element is equal to the corresponding value in $d[]$, all the other other pairs are old. |
| 89 | +Therefore we need to make a small modification: |
| 90 | +at the beginning of each iteration, after extracting the next pair, we check if it an important pair or if it is already an old and handled pair. |
| 91 | +This check is important, otherwise the complexity can increase up to $O(n m)$. |
| 92 | +
|
| 93 | +By default a `priority_queue` sorts elements in descending order. |
| 94 | +To make it sort the elements in ascending order, we can either store the negated distances in it, or pass it a different sorting function. |
| 95 | +We will do the second option. |
| 96 | +
|
| 97 | +```cpp dijkstra_sparse_pq |
| 98 | +const int INF = 1000000000; |
| 99 | +vector<vector<pair<int, int>>> adj; |
| 100 | +
|
| 101 | +void dijkstra(int s, vector<int> & d, vector<int> & p) { |
| 102 | + int n = adj.size(); |
| 103 | + d.assign(n, INF); |
| 104 | + p.assign(n, -1); |
| 105 | +
|
| 106 | + d[s] = 0; |
| 107 | + using pii = pair<int, int>; |
| 108 | + priority_queue<pii, vector<pii>, greater<pii>> q; |
| 109 | + q.push({0, s}); |
| 110 | + while (!q.empty()) { |
| 111 | + int v = q.top().second; |
| 112 | + int d_v = q.top().first; |
| 113 | + q.pop(); |
| 114 | + if (d_v != d[v]) |
| 115 | + continue; |
| 116 | +
|
| 117 | + for (auto edge : adj[v]) { |
| 118 | + int to = edge.first; |
| 119 | + int len = edge.second; |
| 120 | + |
| 121 | + if (d[v] + len < d[to]) { |
| 122 | + d[to] = d[v] + len; |
| 123 | + p[to] = v; |
| 124 | + q.push({d[to], to}); |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | +``` |
| 130 | + |
| 131 | +In practice the `priority_queue` version is a little bit faster than the version with `set`. |
| 132 | + |
| 133 | +### Getting rid of pairs |
| 134 | + |
| 135 | +You can improve the performance a little bit more if you don't store pairs in the containers, but only the vertex indices. |
| 136 | +In this case we must overload the comparison operator: |
| 137 | +it must compare two vertices using the distances stored in $d[]$. |
| 138 | + |
| 139 | +As a result of the relaxation, the distance of some vertices will change. |
| 140 | +However the data structure will not resort itself automatically. |
| 141 | +If fact changing distances of vertices in the queue, might destroy the data structure. |
| 142 | +As before, we need to remove the vertex before we relax it, and then insert it again afterwards. |
| 143 | + |
| 144 | +Since we only can remove from `set`, this optimization is only applicable for the `set` method, and doesn't work with `priority_queue` implementation. |
| 145 | +In practice this significantly increases the performance, especially when larger data types are used to store distances, like `long long` or `double`. |
0 commit comments