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

Автор GreatRevan, история, 12 месяцев назад, По-английски

I thought unordered_set was faster because it doesn't need to deal with sorting.

I got accepted for problem C on a recent Div.3 contest, but it returned as TLE on test 17 after contest finished and I lost 52 points. You know what's funny? When you replace unordered_set with normal set, it gives accepted (sorting ability of normal set doesn't help you for this problem)

Code with unordered_set (TLE on test 17): https://mirror.codeforces.com/contest/2106/submission/317003071

Same code with normal set (Accepted): https://mirror.codeforces.com/contest/2106/submission/317364054

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

»
12 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

It’s due to hash attacks. You can mitigate this by using a custom hasher.

»
12 месяцев назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Yes'nt. In theory, unordered set's operations are much faster than set(1 vs logn). Butt, due to collision, sometimes unordered_set operation can take up to O(n). Check this blog

»
12 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

In some cases if hashing is bad(hash collisions) , then the time complexity of later one increases . It happens in worst cases only , overall unordered_set is better than set .

»
12 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

unordered_set meant to be faster than normal set in normal cases, but in worst case all elements goes into the same bucket due to hash collisions which leads to O(n) per operation.

Avoid using unordered_set or unordered_map as much as you can for not getting TLE.