PrevNext
Not Frequent
 0/19

Shortest Paths with Non-Negative Edge Weights

Authors: Benjamin Qi, Andi Qu, Qi Wang, Neo Wang

Bellman-Ford, Floyd-Warshall, and Dijkstra.

Nearly all Gold shortest path problems involve Dijkstra. However, it's a good idea to learn Bellman-Ford and Floyd-Warshall first since they're simpler.

Bellman-Ford

Resources
CPH

up to but not including "Negative Cycles"

Floyd-Warshall

Tutorial

Resources
CPH

example calculation, code

cp-algo

code, why it works

PAPS

code, why it works

CP2

Optional: Incorrect Floyd-Warshall

From this paper:

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.

Problem

Focus Problem – try your best to solve this problem before continuing!

Explanation

This problem asks us to compute shortest paths between any two vertices. Hence, Floyd-Warshall is suitable because of the low N(N500)N (N \le 500), and the inclusion of negative weights.

Implementation

Time Complexity: O(N3)\mathcal{O}(N^3)

C++

#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
constexpr long long BIG = 1e18; // We can't use LLONG_MAX because of overflow
int main() {

Java

import java.io.*;
import java.util.*;
public class ShortestRoutesII {
// We can't use Long.MAX_VALUE because of overflow
private static final long BIG = (long)1e18;
public static void main(String[] args) {
Kattio io = new Kattio();

Python

Warning!

Due to Python's bad constant factor, this code TLEs on a couple of test cases.

# 1e18 is used instead of float('inf') for performance reasons
BIG = int(1e18)
n, m, q = map(int, input().split())
min_dist = [[BIG] * n for _ in range(n)]
for _ in range(m):
a, b, c = map(int, input().split())
a, b = a - 1, b - 1

Problems

This algorithm is used as the first step of the following:

StatusSourceProblem NameDifficultyTags
GoldHard
Show TagsAPSP, DP

Dijkstra

Tutorial

O(N2)\mathcal{O}(N^2)

Resources
cp-algo

O(MlogN)\mathcal{O}(M\log N)

O(MlogN)\mathcal{O}(M\log N) Implementation

Resources
Benq

Problem

Focus Problem – try your best to solve this problem before continuing!

Implementation

Time Complexity: O(N+MlogN)\mathcal{O}(N + M\log N)

Here's an animation of how the algorithm works:

C++

Recall from the second prerequisite module that we can use greater<> to make the top element of a priority queue the least instead of the greatest. Alternatively, you can negate distances before placing them into the priority queue.

#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
// Adjacency list of (neighbour, edge weight)
vector<vector<pair<int, int>>> neighbors(n);
for (int i = 0; i < m; i++) {

Java

import java.io.*;
import java.util.*;
public class ShortestRoutesI {
Code Snippet: Pair Class (Click to expand)
public static void main(String[] args) {
Kattio io = new Kattio();
int n = io.nextInt();

Python

import heapq
n, m = map(int, input().split())
# Adjacency list of (neighbour, edge weight)
graph = [[] for _ in range(n)]
for i in range(m):
a, b, c = map(int, input().split())
graph[a - 1].append((b - 1, c))

Warning!

It's important to include continue. This ensures that when all edge weights are non-negative, we will never go through the adjacency list of any vertex more than once. Removing it will cause TLE on the last test case of the above problem!

The last test case contains 100000 destinations and 149997 flights. City 1 has flights to cities 2 through 50000. Cities 2 through 50000 have flights to city 50001. City 50001 has flights to cities 50002 through 100000. Without the continue, after the program pops cities 1 through 50000 off the queue, the priority queue will contain 49999 routes that end at city 50001. Every one of the 49999 times city 50001 is popped off the queue and processed, we must iterate over all of its outgoing flights (to cities 50002 through 100000). This results in a runtime of Θ(N2logN)\Theta(N^2\log N), which will TLE.

On the other hand, if we did include the continue, the program will never iterate through the adjacency list of city 50001 after processing it for the first time.

Optional: Faster Dijkstra

Can be done in O(M+NlogN)\mathcal{O}(M+N\log N) with Fibonacci heap. In practice though, this is rarely faster, since the Fibonacci heap has a bad constant factor.

Problems

StatusSourceProblem NameDifficultyTags
CSESEasy
Show TagsSP
GoldEasy
Show TagsSP
GoldEasy
Show TagsSP
GoldEasy
Show TagsSP
GoldNormal
Show TagsSP
CFNormal
Show TagsBinary Search, Coordinate Compression, DP, SP
CSESNormal
Show TagsSP
KattisNormal
Show TagsSP
CSESNormal
Show TagsSP
ACHard
Show TagsGreedy, SP
IOIHard
Show TagsSP
JOIHard
Show TagsDP, SP
JOIHard
Show TagsSP
APIOHard
Show TagsGeometry, SP
Balkan OIHard
Show TagsSP
Balkan OIVery Hard
Show TagsSP, Stack

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext