I'm trying to move from using Java for CP to C++. As such I'm missing some knowledge, but usually I'm able to google it. Today I encountered something that doesn't make sense for me and wasn't able to find good answer for that. In this solution for latest Div 3 contest (problem D) I used unordered_map and received TLE. Then I changed it to map and got Accepted.
I know that what are the differences between map and unordered_map, but I would expect unordered_map to be even faster then map. Does hashing ints really creates so many conflicts, or I'm missing something (for example initialization of size of hash table)?
I think map guarantees you O(logn) but unordered_map can be O(n) in the worst case.
They usually include testcases where the numbers are such that unordered_map degenerates to O(n) caused by hash collisions. Simply use map instead.
sometimes you need O(1) while O(logn) is slow. But I found this in comments: https://codeforces.com/blog/entry/62393 so I guess there I will find answer
use this custom hash
I was able to make an unordered_map solution pass: 85405513
This line does the trick:
It runs in 2/3 the time compared to my solution using map. Im not sure why it works though, and its reliability.