THINK FIRST·CODE LATER

← All labs

Prim's minimum spanning tree

Problem

A campus wants to connect n buildings with cable as cheaply as possible. Write PrimMst. Read n m and m undirected edges u v weight. Starting from vertex 0, grow a tree: keep the edges leaving the tree in a PriorityQueue ordered by weight, repeatedly take the cheapest one, skip it if its far end is already in the tree, otherwise add it and insert the new vertex's edges.

Print each edge added, then the total weight (or Graph is not connected: only k of n vertices reached) and how many stale edges were skipped (this last line depends on your implementation and is not checked).

For the input

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

the program prints

add 0 - 1 (2)
add 1 - 2 (3)
add 1 - 4 (5)
add 0 - 3 (6)
MST weight: 16 with 4 edges
Stale edges skipped: 0

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

5 7
0 1 2
0 3 6
1 2 3
1 3 8
1 4 5
2 4 7
3 4 9
What your program must print for d16-3-data-1.txt
add 0 - 1 (2)
add 1 - 2 (3)
add 1 - 4 (5)
add 0 - 3 (6)
MST weight: 16 with 4 edges

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

Windows PowerShell does not understand <:

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