Я думал что unordered_map быстрее чем map в cpp, но до этого случая..: Во вчерашнем соревнований Div3 в задаче D я использовал unordered_map для хранения элементов, думая что это будет быстрее, но кто-то взломал мой код, а моего друг который имел почти такой же код, но использовавший map вместо unordered_map, не смогли взломать. Почему моего кода взломали, ведь unordered_map быстрее чем просто map, не так ли? Я не смог достичь чёткого ответа этому вопросу. Так что прошу от уважаемого сообщества Codeforces, почему так вышло? Заранее спасибо, за ответ.









unordered_map is basically O(1) for "random" inputs, but since the problemsetters/(people who make hacks) know that people will try using it, they can basically make an input that will "break" the unordered map and make it O(n) per access. Map on the other hand is always O(logn), and so its alot more safe to use.
I did the exact same thing. This article explains very well why the
unordered_mapfails and also discusses the solution to avoid such hacks in the future.Using gp_hash_table<int,int>mp works better than unordered_map because in the worst case, gp_hash_table operates in O(1), while unordered_map can degrade to O(n).Therefore, gp_hash_table is a better choise than unordered_map. If you use gp_hash_table, you need to include the following headers:
The article referenced above says it is even easier to hack than unordered_map.
gp_hash_tablecan be hacked too.You can hack
gp_hash_tableby constructing a sequence $$$A$$$ that satisfies $$$A_i=65537i$$$.Then its time complexity will become $$$O(n)$$$.
You can use this to prevent it from being hacked:
UPD: There is a typo in my code, so I fixed it.
Basically the unordered_map hack is that you put a lot of multiples of a special prime that'll make the unordered_map not being able to resize correctly. It'll put all of those numbers in a single "bucket" which is like a normal array, so searching in that array will take $$$O(n)$$$ time, thus causing the operation time to be $$$O(n)$$$. So your complexity goes up to $$$O(n^2)$$$ which is not what you want. To fix this problem you can use a custom hash function as described here, which will make the hash unpredictable so the hashes can't trigger the special prime.