866. Merging Many Sorted Lists
You are given k lists, each already sorted in non-decreasing order. Print
every value merged into one non-decreasing sequence.
Concatenating everything and sorting works and costs O(N log N) over all N
values, throwing away the fact that each list was already sorted.
A heap uses it. Hold one value from each list, always take the smallest, then
push the next value from whichever list it came from. The heap never holds more
than k values, so the cost is O(N log k), and when k is small against N
that is a real difference.
Note what the heap is doing: it is not sorting the data, it is answering
"which of these k candidates is smallest" over and over while the candidates
change.
Constraints - `1 ≤ k ≤ 1000` - `0 ≤ m ≤ 1000` - The total number of values is at most 200000. - `-1000000000 ≤ value ≤ 1000000000`
Input
The first line contains an integer k.
Each of the next k lines describes one list: an integer m, then m space-separated integers in non-decreasing order.
Output
Print every value in non-decreasing order, separated by single spaces. Print none if there are no values at all.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.