JasonMendoza2008's blog

By JasonMendoza2008, history, 3 months ago, In English

Consider this problem (https://codeforces.me/contest/984/problem/D).

Solution one (https://codeforces.me/contest/984/submission/276446617) uses two recursive self-explanatory functions (compute_f, and compute_max_xor) that use unordered_map for memoization. It does not pass (2000 ms TLE).

Solution two (https://codeforces.me/contest/984/submission/276446798) is the same from a logic point of view (dp corresponds to compute_f and dp_max corresponds to compute_max_xor), except it uses Dynamic Programming. It passes in 546 ms.

I thought it could be that different because of hash collisions. Some people hack some other people by using clever inputs that blow up hashmaps ... but adding a random custom_hash did not help whatsoever.

Is the overhead of using an unordered_map that HIGH? Big enough to bring a x4 in time? Or am I missing something else?

Thank you!

EDIT Keeping memoization but using a 2D array instead of an unordered map did the trick. https://codeforces.me/contest/984/submission/276544726. Crazy. Thank you for your help!

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by JasonMendoza2008 (previous revision, new revision, compare).

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by JasonMendoza2008 (previous revision, new revision, compare).

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

In the first request, you do not respond quickly to the request It’s hard for me to say for how long. And in the second, they made a preconception and responded to a request from O(1)

  • »
    »
    3 months ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    well because there is a cache it won't ever be longer, complexity wise, than filling up the whole dp array

»
3 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Unordered map is pretty slow compared to array look up. At the end of the day, unordered map is a hash table which is just an array but with the added step of converting the key to the index in the table with hashing. Hashing is not the quickest operation.

Hopefully it's clear why this is much slower than an array.

»
3 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Yes, the combined overhead of unordered_map and recursion can easily cause a 4x slowdown. But the iterative DP approach with vectors is more efficient, avoiding the significant costs associated with hashing and recursion. i think This is the key difference between the two solutions.