Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 1 addition & 18 deletions data_structure/test/assosiative_array.test.cpp
Original file line number Diff line number Diff line change
@@ -1,24 +1,7 @@
#define PROBLEM "https://judge.yosupo.jp/problem/associative_array"
#include "../../random/custom_hash.hpp"
#include <iostream>
#include <unordered_map>

#include <chrono>
struct custom_hash {
// <https://codeforces.com/blog/entry/62393>
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}

size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM =
std::chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;

Expand Down
22 changes: 16 additions & 6 deletions random/custom_hash.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#pragma once
#include <chrono>
#include <cstdlib>
#include <functional>

struct custom_hash {
// https://codeforces.com/blog/entry/62393
Expand All @@ -19,10 +20,19 @@ struct custom_hash {
}
};

// Usage
#include <unordered_map>
std::unordered_map<int, int, custom_hash> robust_unordered_map;
// Template of std::hash for arbitrary structs
// template <> struct std::hash<T> {
// std::size_t operator()(const T &x) const noexcept {
// static custom_hash h;
// return h(/* */);
// }
// };

#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
gp_hash_table<int, null_type, custom_hash> robust_hash_table; // fast unordered_set / unordered_map
// robust unordered_map
// #include <unordered_map>
// std::unordered_map<int, int, custom_hash> robust_unordered_map;

// fast unordered_set / unordered_map
// #include <ext/pb_ds/assoc_container.hpp>
// using namespace __gnu_pbds;
// gp_hash_table<int, null_type, custom_hash> fast_hash_table;
11 changes: 11 additions & 0 deletions random/custom_hash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
title: Custom hash functions (各種データ構造のためのハッシュ関数)
documentation_of: ./custom_hash.hpp
---

Codeforces 等で `std::unordered_set<>` や `std::unordered_map<>` を使用した場合のハッシュ衝突攻撃を防止するハッシュ関数.また,任意の構造体をこれらのキーとして与えるための `std::hash` の特殊化のテンプレートを含む.

## Link

- [Blowing up unordered_map, and how to stop getting hacked on it - Codeforces](https://codeforces.com/blog/entry/62393)
- [<unordered_set> [🟢C++20 対応]|競プロのための標準 C++](https://zenn.dev/reputeless/books/standard-cpp-for-competitive-programming/viewer/unordered_set)