Given N > 0
and M > 0
, I want to enumerate all (x, y) pairs such that 1 <= x <= N and 1 <= y <= M in descending order of (x * y).
An
Here's an O(K logK) solution, where K is the number of terms you want to generate.
Edit: Q keeps only one copy of each element; an insert fails if the element is already present.
priority_queue Q
Q.insert( (N*M, (N,M)) ) // priority, (x,y)
repeat K times:
(v, (x,y)) = Q.extract_max()
print(v, (x,y))
Q.insert( (x-1)*y, (x-1,y) )
Q.insert( x*(y-1), (x,y-1) )
This works because before visiting (x,y) you must visit either (x+1,y) or (x,y+1). The complexity is O(KlogK) since Q at most 2K elements are pushed into it.