views:

107

answers:

1

The problem is to access a series of values by two different methods. First, by priority; that is implemented simply enough with a heap. Additionally, it must be possible to "tag" each value with one or more symbols through which a list of items may be accessed.

This would be easy enough to implement efficiently by referencing the same data in two different structures. However, these must form a cohesive queue. Therefore, items removed through the one structure must also be removed from the other, an operation for which a heap is not extremely suitable.

Is there a data structure which is able to provide efficient ordering by one value (ideally optimized for pushing/popping), without wholly degrading the performance of finding/deleting nodes at arbitrary locations?

+4  A: 

You can delete any element from a binary heap in O(log(n)) time if you know which one to delete. Any node can be treated as a valid "sub-heap" and you can use the delete-max (or delete-min) operation just as you would on the whole thing.

The only problem is how do you know which one to delete? I think I have a solution for that. Use a wrapper for the stored class that has a reference to its heap node and delete that node from the wrappers destructor. When you want to remove any element from the collection you can just delete the wrapper through any of the indexes and it will take care of the rest. When you insert something to the collection you need to create a wrapper object and pass a reference to its heap node.

Here is some C++ code:

template <class T> class Wrapper {
    T data;
    HeapNode* index_heap;
    Foo* index_tags;
    Bar* index_queue;

    public: ~Wrapper() {
        index_heap->delete_max();
        index_tags->delete_foo();
        index_queue->delete_bar();
    }
};
stribika