Enumerate grid points on 2D plane with descending order of (x * y)

前端 未结 8 1362
轻奢々
轻奢々 2021-02-09 11:55

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

8条回答
  •  一个人的身影
    2021-02-09 12:20

    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.

提交回复
热议问题