Skip to content

Commit 53c5d90

Browse files
committed
test: added test for hashmap
1 parent e9035a6 commit 53c5d90

2 files changed

Lines changed: 44 additions & 11 deletions

File tree

src/alfred/data_structure/hashmap.hpp

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
#include <vector>
66

77
template <class K, class V>
8-
struct HashedMap {
8+
struct HashMap { // HashMap for integer keys.
99
using u32 = unsigned int;
1010
struct Node {
1111
K key;
@@ -16,38 +16,47 @@ struct HashedMap {
1616
std::vector<u32> fi;
1717
std::vector<Node> e;
1818
inline void init(u32 sz) {
19-
sz += 1;
2019
u32 lim = 1;
21-
while (lim < sz) lim <<= 1;
20+
for (sz++; lim < sz; lim <<= 1);
2221
fi.assign(lim, 0), tot = 0;
2322
mask = lim - 1, e.resize(sz);
2423
}
25-
inline void inc(K x) {
24+
inline void inc(K x, V delta) {
2625
u32 u = x & mask;
2726
for (u32 i = fi[u]; i; i = e[i].ne) {
2827
if (e[i].key == x) {
29-
e[i].val++;
28+
e[i].val += delta;
3029
return;
3130
}
3231
}
33-
e[++tot] = {x, 1, fi[u]}, fi[u] = tot;
32+
e[++tot] = {x, V() + delta, fi[u]}, fi[u] = tot;
3433
}
35-
inline void dec(K x) {
34+
inline void set(K x, V v) {
3635
u32 u = x & mask;
3736
for (u32 i = fi[u]; i; i = e[i].ne) {
3837
if (e[i].key == x) {
39-
e[i].val--;
38+
e[i].val = v;
4039
return;
4140
}
4241
}
43-
e[++tot] = {x, 1, fi[u]}, fi[u] = tot;
42+
e[++tot] = {x, v, fi[u]}, fi[u] = tot;
4443
}
45-
inline V query(K x) {
44+
// this method does not create new element, returns V() by default.
45+
inline V get(K x) {
4646
u32 u = x & mask;
4747
for (u32 i = fi[u]; i; i = e[i].ne) {
4848
if (e[i].key == x) return e[i].val;
4949
}
50-
return 0;
50+
return V();
51+
}
52+
// this method creates new element.
53+
inline V &operator[](K x) {
54+
u32 u = x & mask;
55+
for (u32 i = fi[u]; i; i = e[i].ne) {
56+
if (e[i].key == x) return e[i].val;
57+
}
58+
e[++tot] = {x, V(), fi[u]}, fi[u] = tot;
59+
return e[tot].val;
5160
}
5261
};
5362

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// competitive-verifier: PROBLEM https://judge.yosupo.jp/problem/associative_array
2+
3+
#include "../../src/alfred/config/io-sync-off.hpp"
4+
#include "../../src/alfred/data_structure/hashmap.hpp"
5+
#include <iostream>
6+
7+
int q, opt;
8+
using u64 = unsigned long long;
9+
10+
int main(int argc, char const *argv[]) {
11+
u64 x, v;
12+
optimizeIO();
13+
HashMap<u64, u64> mp;
14+
std::cin >> q, mp.init(q);
15+
while (q--) {
16+
std::cin >> opt >> x;
17+
if (opt == 0) {
18+
std::cin >> v, mp.set(x, v);
19+
} else {
20+
std::cout << mp.get(x) << '\n';
21+
}
22+
}
23+
return 0;
24+
}

0 commit comments

Comments
 (0)