Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a large priority queue with the most relevant items?

In an optimization problem I keep in a queue a lot of candidate solutions which I examine according to their priority.

Each time I handle one candidate, it is removed form the queue but it produces several new candidates making the number of cadidates to grow exponentially. To handle this I assign a relevancy to each candidate, whenever a candidate is added to the queue, if there is no more space avaliable, I replace (if appropiate) the least relevant candidate currently in the queue with the new one.

In order to do this efficiently I keep a large (fixed size) array with the candidates and two linked indirect binary heaps: one handles the candidates in decreasing priority order, and the other in ascending relevancy.

This is efficient enough for my purposes and the supplementary space needed is about 4 ints/candidate which is also reasonable. However it is complicated to code, and it doesn't seem optimal.

My question is if you know of a more adequate data structure or of a more natural way to perform this task without losing efficiency.

like image 234
Esteban Crespi Avatar asked Jan 04 '11 00:01

Esteban Crespi


1 Answers

Here's an efficient solution that doesn't change the time or space complexity over a normal heap:

In a min-heap, every node is less than both its children. In a max-heap, every node is greater than its children. Let's alternate between a min and max property for each level making it: every odd row is less than its children and its grandchildren, and the inverse for even rows. Then finding the smallest node is the same as usual, and finding the largest node requires that we look at the children of the root and take the largest. Bubbling nodes (for insertion) becomes a bit tricker, but it's still the same O(logN) complexity.

Keeping track of capacity and popping the smallest (least relevant) node is the easy part.

EDIT: This appears to be a standard min-max heap! See here for a description. There's a C implementation: header, source and example. Here's an example graph:


(source: chonbuk.ac.kr)

like image 84
moinudin Avatar answered Oct 27 '22 09:10

moinudin