Could you, please, help me with the data structure that allows O(logN) (or at least O(sqrtN)) operations for the following:
- Insert an item having
ID(int64_t) andhealth(double) - Remove an item by
ID - Find an item that is weighted random by
health
The preferred language is C++ or C. By the weighted random I mean the following:
Consider totalHealth=Sum(health[0], health[1], ..., health[N-1]). I need a fast (as described above) operation that is equivalent to:
- Compute
const double atHealth = rand_uint64_t()*totalHealth/numeric_limits<uint64_t>::max(); - Iterate over
i=0 to N-1to find the firstisuch thatSum(health[0], health[1], ..., health[i]) >= atHealth
Constraints: health[i] > 0, rand_uint64_t() returns a uniformly distributed integer value between 0 and numeric_limits<uint64_t>::max().
What I have tried so far is a C++ unordered_map that allows quick (Θ(1)) insertion by ID and removal by ID, but the operation #3 is still linear in N as described in my pseudo-code above.
You help is very appreciated!