Module: Dijkstra's algorithm


Problem

8/14

Dijkstra's algorithm in O(M logN) c set: Start (C++)

Theory Click to read/hide

Since the asymptotic behavior of the naive implementation of Dijkstra's algorithm is: \(O(n^2 + m)\), then as the number of vertices increases, the speed of work becomes unsatisfactory.
 Various data structures can be used for improvement: Fibonacci heaps, set sets, or a priority queue priority_queue. 
Consider an example with set, as a result, the final asymptotics is: \(O(n log (m))\), details.

Problem

You are given a directed weighted graph. Find the shortest distance from one given vertex to another.
 
Input
The first line contains three numbers: N, M, S and F (1≤ N≤ 100, 1≤ S, F≤ N), where N – number of graph vertices, M – number of ribs,  S– initial vertex, and F – final. In the next N lines, enter N numbers each, not exceeding 100, – graph adjacency matrix, where -1 means no edge between vertices, and any non-negative number – the presence of an edge of given weight. Zeros are written on the main diagonal of the matrix.
 
Output
It is required to display the desired distance or -1 if there is no path between the specified vertices.

Examples
# Input Output
1 4 4 3 4
3 1 3
1 2 3
2 4 3
3 4 10
9