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

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

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, pair<int, int>> mp;

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

Thanks for reading <3:

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

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

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

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

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

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

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