A data structure that always stores n-best elements

I need a data structure that always contains the nlargest elements inserted so far (in a specific order).

So, if nequal to 3, we could have the following session, in which I insert several numbers, and the contents of the container change:

[]  // now insert 1
[1] // now insert 0
[1,0] // now insert 4
[1,0,4] // now insert 3
[1,4,3] // now insert 0
[1,4,3] // now insert 3
[4,3,3]

You get the idea. What is the name of the data structure? What is the best way to implement this? Or is it in some kind of library?

I am thinking of using a container that has priority_queue(delegation) for its elements, which uses inverse comparison, so it popwill remove the smallest element. Thus, the function insertfirst checks whether the new item to be inserted is larger than the smallest. If so, we discard this smallest and click on the new item.

(I have an implementation C++, but the question is still an agnostic language.)

+8
source share
7 answers

, , , . - ; , , N = 2 ^ n N-1.

, ( A) n:

  • A [0]; A [1] node
  • node A [k], A [2 * k] A [2 * k + 1]
  • A [N/2..N-1] -

"", , node ( ) . " ":

  • A [k] <= A [2 * k]
  • A [k] <= A [2 * k + 1]

N:

  • , A [1] .
  • (x) : (x < A [1]), .
  • , :
    • (A [1], )
    • (A [1]: = x)
    • :
      • x ,
      • , swap x
      • ,

, "" , . n = log2 (N) , , . , ; , , .

+12

_queue - ++ STL. , , .

- (, , - ):

  • n-

std:: priority_queue 2.

+4

Java SortedSet, . TreeSet. , , , .

, Project Euler.

+4

, ... Java - . EDIT: LinkedBlockingQueue. , ++ STL - .

+2

n ?

+1

, N , "", , N

0

-, .

, ; -.

: O (1) insert, get-min O (log log n) extract-min. [1] O (log n) O (1) . [2]


[1]M. Thorup, “Entire priority queues with decreasing key in constant time and the problem with one source of shortest paths”, in the materials of the thirty-fifth annual symposium ACM on the theory of computing, New York, New York, USA, 2003, pp. 149-158.

[2]GS Brodal, G. Lagogiannis, C. Makris, A. Tsakalidis, and K. Tsichlas, “Optimal finger search trees on a pointing machine,” J. Comput. Syst. Sci., Vol. 67, no. 2, p. 381-418, September 2003

-1
source

All Articles