-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_double_hashing.cpp
More file actions
121 lines (107 loc) · 2.42 KB
/
Copy pathhash_double_hashing.cpp
File metadata and controls
121 lines (107 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
* hash_double_hashing
*/
#include <iostream>
#define DIV1 353333
#define DIV2 17
using namespace std;
struct Item {
int item;
Item() {}
Item(int data) : item(data) {}
};
class Hash {
private:
int *flag;
Item *item;
public:
Hash() {
flag = new int[DIV1];
for (int i = 0; i < DIV1; i++) {
flag[i] = 1;
}
item = new Item[DIV1];
}
int hash_code1(int key) {
return key % DIV1;
}
int hash_code2(int key) {
return DIV2 - key % DIV2;
}
void insert(int key) {
int index = hash_code1(key);
int i = index;
while (true) {
if (flag[i] == 1 || flag[i] == -1) {
item[i] = key;
flag[i] = 0;
return;
}
i = i + hash_code2(key);
i = i % DIV1;
if (i == index) {
return;
}
}
}
void search(int key) {
int index = hash_code1(key);
int i = index;
while (true) {
if (flag[i] == 0 || flag[i] == -1) {
if (item[i].item == key) {
cout << 1 << endl;
return;
}
i = i + hash_code2(key);
i = i % DIV1;
if (i == index) {
cout << 0 << endl;
return;
}
}
if (flag[i] == 1) {
cout << 0 << endl;
return;
}
}
}
void remove(int key) {
int index = hash_code1(key);
int i = index;
while (true) {
if (flag[i] == 0 || flag[i] == -1) {
if (item[i].item == key) {
item[i] = -1;
flag[i] = -1;
return;
}
i = i + hash_code2(key);
i = i % DIV1;
if (i == index) {
cout << 0 << endl;
return;
}
}
if (flag[i] == 1) {
cout << 0 << endl;
return;
}
}
}
};
int main() {
Hash hash;
int N, M, input;
cin >> N;
for (int i = 0; i < N; i++) {
cin >> input;
hash.insert(input);
}
cin >> M;
for (int i = 0; i < M; i++) {
cin >> input;
hash.search(input);
}
return 0;
}