一个解法可以是
q : priority queue (decreasing) := empty priority queue
add (0, 0) to q with priority a[0] + b[0]
while k > 0:
k--
x := pop q
output x
(i, j) : tuple of int,int := position of x
if i < m:
add (i + 1, j) to q with priority a[i + 1] + b[j]
if j < n:
add (i, j + 1) to q with priority a[i] + b[j + 1]
- The loop is executed k times.
- There is one pop operation per iteration.
- There are up to two insert operations per iteration.
- The maximum size of the priority queue is
O(min(m, n))O(m + n).- The priority queue can be implemented with a binary heap giving log(size) pop and insert.
- Therefore this algorithm is
O(k * log(min(m, n)))O(k * log(m + n)).
但注意可能有重复的值被添加,所以在填入q中时要先判断是否已存在,出队时删除其存在。用一个set可以方便的判断。