Problem 598
Smallest Range Covering Elements from K Lists
Hard · 30 pts · Heap, Sliding Window, Sorting
Problem
You are given K lists of integers, each sorted in non-decreasing order. Find the smallest range [a, b] that contains at least one number from every list. Range [a, b] is smaller than [c, d] if b - a < d - c, or if they are equally wide and a < c. Keep one pointer per list and a min-heap of the current elements: the range is [heap minimum, current maximum]; then advance the list holding the minimum, until some list runs out.
Input
The first line contains K. Each of the next K lines starts with the list length, followed by the sorted values of that list.
Output
Print a and b separated by a space.
Constraints
1 <= K <= 3500; 1 <= list length <= 50; -10^5 <= values <= 10^5
Example input
3 5 4 10 15 24 26 4 0 9 12 20 4 5 18 22 30
Example output
20 24
Explanation
For the lists 4 10 15 24 26 / 0 9 12 20 / 5 18 22 30, the range [20, 24] contains 24, 20 and 22, one from each list. No narrower range works, so the answer is 20 24.