THINK FIRST·CODE LATER

← All labs

Bellman–Ford: shortest paths with negative edges

Problem

Dijkstra's algorithm fails when edges can be negative (a refund, a downhill energy gain, an exchange-rate advantage). Write BellmanFord. Read n m source and m directed edges u v weight. Relax every edge, in input order, n − 1 times (stop early when a whole round changes nothing). Then run one more round: if any distance can still improve, a negative cycle is reachable.

Print the number of rounds used (not checked), then either Negative cycle reachable from s: shortest paths are not defined or, for each vertex, the distance and the path (unreachable if there is none).

For the input

5 10 0
0 1 6
0 2 7
1 2 8
1 3 5
1 4 -4
2 3 -3
2 4 9
3 1 -2
4 0 2
4 3 7

the program prints

Rounds used: 3
0 -> 0: 0  path 0
0 -> 1: 2  path 0 2 3 1
0 -> 2: 7  path 0 2
0 -> 3: 4  path 0 2 3
0 -> 4: -2  path 0 2 3 1 4

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d16-4-data-1.txt

5 10 0
0 1 6
0 2 7
1 2 8
1 3 5
1 4 -4
2 3 -3
2 4 9
3 1 -2
4 0 2
4 3 7
What your program must print for d16-4-data-1.txt
0 -> 0: 0  path 0
0 -> 1: 2  path 0 2 3 1
0 -> 2: 7  path 0 2
0 -> 3: 4  path 0 2 3
0 -> 4: -2  path 0 2 3 1 4

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d16-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d16-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.