map fails, where gp_hash_table wins

Revision en3, by -739397, 2026-05-22 08:06:06

In the last contest, my solution for Problem C got TLE with map, but after switching to gp_hash_table + custom hash, the same logic passed in ~375ms.

map takes O(log n) time for each operation, while gp_hash_table is usually much faster with average O(1) complexity. But default hashing can sometimes be exploited with specially crafted test cases, making it as slow as O(n). Using a custom hash helps avoid those collisions and keeps the performance fast in practice. For more details you may consider this blog.

TLE submission: 375591424

AC submission: 375591617

How to use it ??

Templete:

#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
struct chash {
	const uint64_t C = 4e18*acos(0)+71;
	const int R = chrono::steady_clock::now().time_since_epoch().count();
	size_t operator()(uint64_t x) const {
		return __builtin_bswap64((x^R)*C);
	}
};
template <class K, class V> using HT = gp_hash_table<K, V, chash>;
template <class K, class V> V get(HT<K, V> &u, K x) {
	auto it = u.find(x); return it == u.end() ? 0 : it->second;
}

Usage:

Like map,

  • HT<int, int> cnt;
  • HT<int, pari<int, int>> mp;

So, I think it’s high time to add this optimization trick to your CP journey.

Thanks for reading <3:

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English -739397 2026-05-22 08:13:48 2 Tiny change: 'HT<int, pari<int, int>' -> 'HT<int, pair<int, int>'
en3 English -739397 2026-05-22 08:06:06 2
en2 English -739397 2026-05-22 08:05:26 20
en1 English -739397 2026-05-22 08:04:12 1496 Initial revision (published)