THINK FIRST·CODE LATER

← All labs

Dijkstra: distances from a source

Problem

Read a directed graph with non-negative integer weights and a source s, and print the shortest distance from s to every vertex.

Input

n m s        // vertices 0 .. n-1, number of edges, source
u1 v1 w1     // m lines: directed edge u -> v with weight w (0 <= w <= 2,000,000,000)
...

Parallel edges are allowed.

Output — one line per vertex, in increasing vertex order: v: d, or v: INF if v cannot be reached from s. For

6 10 0
0 4 7
0 3 2
3 4 3
3 1 8
4 1 1
3 5 10
1 5 2
5 2 3
1 2 6
4 2 12

the output is

0: 0
1: 6
2: 11
3: 2
4: 5
5: 8

Use a PriorityQueue (lazy deletion is fine). Distances can exceed the int range, so use long.

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-1-data-1.txt

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

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-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d16-1-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.