--- id: sp title: "Shortest Paths with Non-Negative Edge Weights" author: Benjamin Qi prerequisites: - Gold - Breadth First Search description: Introduces Dijkstra's Algorithm for a single source as well as Floyd-Warshall for All-Pairs Shortest Path. frequency: 3 --- import { Problem } from "../models"; export const metadata = { problems: { sample: [ new Problem("CSES", "Shortest Routes I", "1671", "Easy", false, ["SP"], "equivalent to [Kattis SSSP Non-Negative](https://open.kattis.com/problems/shortestpath1)"), ], dijk: [ new Problem("CSES", "Flight Discount", "1195", "Easy", false, ["SP"], "one edge modified"), new Problem("CSES", "Flight Routes", "1196", "Easy", false, ["SP"], "$k$ smallest paths"), new Problem("CSES", "Investigation", "1202", "Easy", false, ["SP"], ""), new Problem("Gold", "Milk Pumping", "969", "Easy", false, ["SP"], ""), new Problem("Gold", "Visit FJ", "717", "Easy", false, ["SP"], ""), new Problem("Gold", "Shortcut", "899", "Easy", false, ["SP"], ""), new Problem("Gold", "Fine Dining", "861", "Easy", false, ["SP"], ""), new Problem("Kattis", "Robot Turtles", "robotturtles", "Easy", false, ["SP"], ""), new Problem("Kat", "Lane Switching", "https://open.kattis.com/contests/acpc17open/problems/laneswitching", "Normal", false, ["SP"], ""), ], apspSam: [ new Problem("CSES", "Shortest Routes II", "1672", "Easy", false, ["APSP"], ""), ], apsp: [ new Problem("Gold", "Moortal Cowmbat", "971", "Hard", false, ["APSP", "DP"], ""), ], } }; ## Tutorial Use *Dijkstra's Algorithm*. code ## Implementation ### Part 1: $O(N^2)$ The USACO training pages present a $O(N^2)$ version, although this is rarely used nowadays. (but describe anyways?) ### Part 2: $O(M\log N)$ (comments in code?) Can be done in $O(M+N\log N)$ with [Fibonacci heap](https://en.wikipedia.org/wiki/Fibonacci_heap). ## Problems ## All Pairs Shortest Path (APSP) Use the *Floyd-Warshall* algorithm. ### Tutorial example calculation, code [Paper](https://arxiv.org/pdf/1904.01210.pdf) > A common mistake in implementing the Floyd–Warshall algorithm is to misorder the triply nested loops (The correct order is `KIJ`). The incorrect `IJK` and `IKJ` algorithms do not give correct solutions for some instance. However, we can prove that if these are repeated three times, we obtain the correct solutions. > > It would be emphasized that these fixes (repeating incorrect algorithms three times) have the same time complexity as the correct Floyd–Warshall algorithm up to constant factors. Therefore, our results suggest that, if one is confused by the order of the triply nested loops, one can repeat the procedure three times just to be safe. ### Problems (more?)