Problem 580
Find K Pairs with Smallest Sums
Medium · 20 pts · Array, Heap, Sorting
Problem
You are given two arrays A and B, each sorted in non-decreasing order, and an integer K. A pair takes one element A[i] and one element B[j]. List the K pairs with the smallest sums A[i] + B[j]. Pairs with equal sums are ordered by i, then by j. Start a min-heap with the pairs (i, 0) and, every time you take out the smallest pair (i, j), push (i, j + 1); this visits the pairs in exactly the required order.
Input
The first line contains N, M and K. The second line contains A (sorted). The third line contains B (sorted).
Output
Print K lines, each with the two values A[i] and B[j] of one pair, in order.
Constraints
1 <= N, M <= 100000; -10^9 <= values <= 10^9; 1 <= K <= min(1000, N × M)
Example input
3 3 3 1 7 11 2 4 6
Example output
1 2 1 4 1 6
Explanation
With A = 1 7 11, B = 2 4 6 and K = 3, the smallest sums are 1 + 2 = 3, 1 + 4 = 5 and 1 + 6 = 7. The next sum, 7 + 2 = 9, is larger, so the three pairs are 1 2, 1 4 and 1 6.