|
4 | 4 | #include <utility> |
5 | 5 | #include <vector> |
6 | 6 |
|
7 | | -template <class K, class V, size_t SIZE = 3301> |
8 | | -struct HashMap { |
9 | | - std::vector<std::pair<K, V>> vec[SIZE]; |
10 | | - HashMap(void) {} |
11 | | - inline int hash_key(K key) { return key % SIZE; } |
12 | | - inline auto find_it(int h, K key) { |
13 | | - return std::find_if(vec[h].begin(), vec[h].end(), [&](auto kv) { |
14 | | - return kv.first == key; |
15 | | - }); |
| 7 | +template <class K, class V> |
| 8 | +struct HashedMap { |
| 9 | + using u32 = unsigned int; |
| 10 | + struct Node { |
| 11 | + K key; |
| 12 | + V val; |
| 13 | + u32 ne; |
| 14 | + }; |
| 15 | + u32 lim, mask, tot; |
| 16 | + std::vector<u32> fi; |
| 17 | + std::vector<Node> e; |
| 18 | + inline void init(u32 sz) { |
| 19 | + sz += 1; |
| 20 | + u32 lim = 1; |
| 21 | + while (lim < sz) lim <<= 1; |
| 22 | + fi.assign(lim, 0), tot = 0; |
| 23 | + mask = lim - 1, e.resize(sz); |
16 | 24 | } |
17 | | - inline void inc(K key) { |
18 | | - int h = hash_key(key); |
19 | | - auto it = find_it(h, key); |
20 | | - if (it == vec[h].end()) { |
21 | | - vec[h].emplace_back(key, 1); |
22 | | - return; |
| 25 | + inline void inc(K x) { |
| 26 | + u32 u = x & mask; |
| 27 | + for (u32 i = fi[u]; i; i = e[i].ne) { |
| 28 | + if (e[i].key == x) { |
| 29 | + e[i].val++; |
| 30 | + return; |
| 31 | + } |
23 | 32 | } |
24 | | - it->second++; |
| 33 | + e[++tot] = {x, 1, fi[u]}, fi[u] = tot; |
25 | 34 | } |
26 | | - inline void dec(K key) { |
27 | | - int h = hash_key(key); |
28 | | - auto it = find_it(h, key); |
29 | | - if (it == vec[h].end()) { |
30 | | - return; |
31 | | - } |
32 | | - it->second--; |
33 | | - if (it->second == 0) { |
34 | | - vec[h].erase(it); |
| 35 | + inline void dec(K x) { |
| 36 | + u32 u = x & mask; |
| 37 | + for (u32 i = fi[u]; i; i = e[i].ne) { |
| 38 | + if (e[i].key == x) { |
| 39 | + e[i].val--; |
| 40 | + return; |
| 41 | + } |
35 | 42 | } |
| 43 | + e[++tot] = {x, 1, fi[u]}, fi[u] = tot; |
36 | 44 | } |
37 | | - inline V get(K key) { |
38 | | - int h = hash_key(key); |
39 | | - auto it = find_it(h, key); |
40 | | - if (it == vec[h].end()) { |
41 | | - return 0; |
| 45 | + inline V query(K x) { |
| 46 | + u32 u = x & mask; |
| 47 | + for (u32 i = fi[u]; i; i = e[i].ne) { |
| 48 | + if (e[i].key == x) return e[i].val; |
42 | 49 | } |
43 | | - return it->second; |
| 50 | + return 0; |
44 | 51 | } |
45 | 52 | }; |
46 | 53 |
|
|
0 commit comments