55#include < vector>
66
77template <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
0 commit comments