Here's an interesting problem:
Let's say we have a set A
for which the following are permitted:
- Insert x
- Find-min x
- Delete the n-th inserted element in A
Create a data structure to permit these in logarithmic time.
The most common solution is with a heap. AFAIK, heaps with decrease-key (based on a value - generally the index when an element was added) keep a table with the Pos[1...N]
meaning the i
-th added value is now on index Pos[i]
, so it can find the key to decrease in O(1). Can someone confirm this?
Another question is how we solve the problem with STL containers? i.e. with sets
, maps
or priority queues
. A partial solution i found is to have a priority queue with indexes but ordered by the value to these indexes. I.e. A[1..N]
are our added elements in order of insertion. pri-queue
with 1..N
based on comparison of (A[i],A[j])
. Now we keep a table with the deleted indexes and verify if the min-value index was deleted. Unfortunately, Find-min becomes slightly proportional with no. of deleted values.
Any alternative ideas?
Now I thought how to formulate a more general problem.
Create a data structure similar to multimap with <key, value>
elements. Keys are not unique. Values are.
Insert, find one (based on key), find (based on value), delete one (based on key) and delete (based on value) must be permitted O(logN).
Perhaps a bit oddly, this is possible with a manually implemented Binary Search Tree with a modification: for every node operation a hash-table or a map based on value is updated with the new pointer to the node.
Similar to having a strictly ordered std::set
(if equal key order by value) with a hash-table on value giving the iterator to the element containing that value.
Possible with std::set
and a (std::map/hash table) as described by Chong Luo.