THINK FIRST·CODE LATER

← All labs

Merging k sorted lists with a priority queue

Problem

Write MergeKLists. Read k, then k sorted lists (size followed by the values). Merge them into one sorted sequence using a PriorityQueue that holds at most one entry per list: the current head of each list (value, list number, index in the list). Repeatedly remove the smallest entry, output it, and insert the next value of the same list. Equal values come out in list order.

Print the merged sequence, the list each value came from (A, B, C …), and the largest size the heap ever had.

For the input

3
3 1 4 9
2 2 3
4 0 5 6 10

the program prints

Merged: 0 1 2 3 4 5 6 9 10
Taken from lists: CABBACCAC
9 values, heap never larger than 3 (k = 3)

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.

d11-4-data-1.txt

3
3 1 4 9
2 2 3
4 0 5 6 10
What your program must print for d11-4-data-1.txt
Merged: 0 1 2 3 4 5 6 9 10
Taken from lists: CABBACCAC
9 values, heap never larger than 3 (k = 3)

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

Windows PowerShell does not understand <:

Get-Content d11-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.