THINK FIRST·CODE LATER

← All labs

Kruskal with union–find

Problem

Read an undirected weighted graph and build a minimum spanning forest with Kruskal's algorithm and a union–find structure (union by size or rank, and path compression).

Input

n m          // vertices 0 .. n-1, number of edges
u1 v1 w1     // m lines: undirected edge with integer weight w
...

Self-loops and parallel edges may appear.

Rules

  • Sort the edges by weight. Edges with equal weight keep their input order (use a stable sort such as List.sort).
  • Scan the edges in that order and accept an edge only if its endpoints are in different sets.

Output — each accepted edge, in the order accepted, written exactly as in the input as u - v : w; then the total weight and the number of connected components (1 for a connected graph). For

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

the output is

4 - 5 : 1
1 - 3 : 2
0 - 2 : 3
0 - 1 : 4
5 - 6 : 4
3 - 4 : 6
Total weight: 20
Components: 1

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

7 11
0 1 4
0 2 3
1 2 5
1 3 2
2 3 7
2 4 8
3 4 6
3 5 9
4 5 1
4 6 5
5 6 4
What your program must print for d16-2-data-1.txt
4 - 5 : 1
1 - 3 : 2
0 - 2 : 3
0 - 1 : 4
5 - 6 : 4
3 - 4 : 6
Total weight: 20
Components: 1

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

Windows PowerShell does not understand <:

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