sojabhai's blog

By sojabhai, history, 4 months ago, In English

Hey Codeforces

I am well aware that we shouldn't use unordered maps in our solutions because they lead to tle in certain cases

I came across some solutions using unordered map for the 4th Question in the recent Edu Round. I tried generating a testcase in which these submissions tle but failed to do so

Can anyone help me out in this

Submission 1 : 273573097 Submission 2 : 273588275 Submission 3 (Its in Java but shouldn't it use TreeMap instead of Map ? ) : 273571369

Thanks a lot :)

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

»
4 months ago, # |
  Vote: I like it +36 Vote: I do not like it

First of all, this map[i] = vi(); manual initialization kinda prevents all the hacks, because to hack unordered_maps we want only very specific 'evil' keys to be inserted in the map, and that is not just 0, 1, 2, .... They should be (multiples of a speicifc prime) + (a constant).

I tried a version with that line erased, but there still is a problem. To make an unordered_map $$$\mathcal{O}(n^2)$$$, we also need at least a range of $$$\mathcal{O}(n^2)$$$ possible keys. In this code, the keys can only be in range $$$[0,199999]$$$, so we can never make it run as slow as $$$200000^2$$$.

There is a small trick to make it run in approximately $$$\mathcal{O}(n^{1.5})$$$ when the key range is $$$\mathcal{O}(n)$$$. To do this, we need an evil value that is close to $$$n^{0.5}$$$, which could be multiples of $$$541$$$ in case of C++20. We can insert $$$~370$$$ different multiples of $$$541$$$, and then repeat the 'worst' key for the rest. From my experiments, the 'worst' key is the first element inserted and it gets faster for the elements inserted later. So this unordered_map will take approximately $$$\mathcal{O}(n^{0.5})$$$ time for each of the $$$\mathcal{O}(n)$$$ accesses, resulting in $$$\mathcal{O}(n^{1.5})$$$.

So yeah, I tried it, but it took only 1405 ms because its constant is not really that high. Sadge. Maybe there could be a better strategy though...

  • »
    »
    4 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Okayy makes sense, so basically is it safe to use unordered map for tree's / graphs cause mostly the constraints are the same ?

    • »
      »
      »
      4 months ago, # ^ |
      Rev. 2   Vote: I like it +6 Vote: I do not like it

      I wouldn't say it's safe, but for $$$n \le 2 \times 10^5$$$ it's quite unlikely to be hacked. With a bit larger $$$n$$$ (like $$$5 \times 10^5$$$) it's more likely to have quite a bad case.

      If you're interested, https://codeforces.net/contest/1985/hacks/1049559 is one of the cases where I tried really hard to find an anti-unordered case in a very harsh constraints, and it shows that when you're doing something close to the TL then these small slowdowns actually matter.