Блог пользователя jerdno

Автор jerdno, история, 4 года назад, По-английски

Hi,

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)?

Thanks.

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I think map guarantees you O(logn) but unordered_map can be O(n) in the worst case.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

They usually include testcases where the numbers are such that unordered_map degenerates to O(n) caused by hash collisions. Simply use map instead.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится
»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I was able to make an unordered_map solution pass: 85405513

This line does the trick:

cnts.reserve(1024);

It runs in 2/3 the time compared to my solution using map. Im not sure why it works though, and its reliability.