All problems

Problem 124

Merge K Sorted Lists

Hard · 30 pts · Linked List, Heap, Divide and Conquer

Problem

You are given K linked lists, each sorted in non-decreasing order; some of them may be empty. Merge them all into a single sorted list and print it. Merging the lists one after another can be slow when K is large. Use a min-heap (priority queue) that holds the current head of every list: repeatedly take the smallest node, append it to the result, and push the next node of its list. With T nodes in total, this takes O(T log K).

Input

First line: integer K. Then for each list: a line with its length L, and a line with its L sorted values (empty if L = 0).

Output

Print the node values of the resulting list from head to tail, space-separated, or EMPTY if it has no nodes.

Constraints

0 <= K <= 10000; 0 <= L; total nodes <= 100000; -10000 <= value <= 10000

Example input

3
3
1 4 5
3
1 3 4
2
2 6

Example output

1 1 2 3 4 4 5 6

Explanation

Merging 1 4 5, 1 3 4 and 2 6 means repeatedly taking the smallest available head: 1, 1, 2, 3, 4, 4, 5, 6. The result is 1 1 2 3 4 4 5 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Reverse Nodes in K-Group Next: Reorder List