Pagini recente » Cod sursa (job #1409871) | Cod sursa (job #844366) | Cod sursa (job #1157633) | Cod sursa (job #72480) | Cod sursa (job #818543)
Cod sursa(job #818543)
#include <cstdio>
class hash_map {
struct hash_key {
int key;
hash_key* next;
};
hash_key** hash_table;
int size;
int odd_number;
int word_size;
int log_size;
int hash_function (int elem) {
int ret = ((long long)elem * odd_number) >> (word_size - log_size);
if (ret < 0 || ret >= size)
while (1);
}
public:
hash_map (int size) {
this->size = size;
hash_table = new hash_key*[size];
for (int i = 0; i < size; i++)
hash_table[i] = NULL;
word_size = 31;
odd_number = 1345874339;
for (log_size = 0; (1 << log_size) <= size; log_size++);
log_size--;
}
~hash_map () {
for (int i = 0; i < size; i++) {
while ( hash_table[i] != NULL) {
hash_key* next = hash_table[i]->next;
delete hash_table[i];
hash_table[i] = next;
}
}
delete hash_table;
}
void Insert (int elem) {
int key = hash_function (elem);
hash_key* original_key = hash_table[key];
hash_table[key] = new hash_key;
hash_table[key]->key = elem;
hash_table[key]->next = original_key;
}
hash_key* Find (int elem) {
int key = hash_function (elem);
for (hash_key* hk = hash_table[key]; hk != NULL; hk = hk->next)
if (hk->key == elem)
return hk;
return NULL;
}
void Delete (int elem) {
int key = hash_function (elem);
hash_key* prev_key = NULL;
hash_key* cur_key = NULL;
for (cur_key = hash_table[key]; cur_key != NULL; cur_key = cur_key->next, prev_key = cur_key)
if (cur_key->key == elem) {
if (prev_key != NULL)
prev_key->next = cur_key->next;
else
hash_table[key] = cur_key->next;
delete cur_key;
return;
}
}
};
int main()
{
freopen ("hashuri.in", "r", stdin);
freopen ("hashuri.out", "w", stdout);
int N, size;
scanf("%d", &N);
for (size = 1; size <= N; size <<= 1);
hash_map H(size >> 1);
for (int i = 0; i < N; i++) {
int req_type;
int elem;
scanf ("%d %d", &req_type, &elem);
switch (req_type) {
case 1: H.Insert(elem); break;
case 2: H.Delete(elem); break;
case 3: printf ("%d\n", H.Find(elem) != NULL ? 1 : 0);
}
}
return 0;
}