Cod sursa(job #739409)

Utilizator gener.omerGener Omer gener.omer Data 23 aprilie 2012 00:01:46
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <iostream>
#include <fstream>

using namespace std;

#define DEFAULT_TABLE_SIZE  65536
#define MIN_THRESHOLD 0.25
#define MAX_THRESHOLD 0.75

struct node{
    int key;
    struct node * next;
};

int size;
struct node ** hash_table;

void init_hash_table(int initSize){
    size = initSize;
    hash_table = new node*[size];
    for(int i = 0; i < size; ++i)
        hash_table[i] = NULL;
}

int hash(int key){
    return key % size;
}

void add_to_hash_table(int key){
    int hash_value = hash(key);
    struct node * new_node = (struct node *) malloc(sizeof(struct node));
    new_node->key = key;
    new_node->next = hash_table[hash_value];
    hash_table[hash_value] = new_node;
}

void remove_element_from_hash_table(int key){
    int hash_value = hash(key);
    node * prev, * current = hash_table[hash_value];
    if(current != NULL){
        if(current->key == key){
            hash_table[hash_value] = current->next;
            free(current);
        }
        else{
            while(current != NULL && current->key != key){
                prev = current;
                current = current->next;
            }
            if(current != NULL){
                if(prev == NULL){
                    free(current);
                    hash_table[hash_value] = NULL;
                }
                else{
                    prev->next = current->next;
                    free(current);
                }
            }
        }
    }
}

int search(int key){
    int hash_value = hash(key);
    node * crt = hash_table[hash_value];
    while(crt != NULL){
        if(crt->key == key)
            return 1;
        crt = crt->next;
    }
    return 0;
}

int main(){
    int N;
    init_hash_table(DEFAULT_TABLE_SIZE);
    ifstream in("hashuri.in");
    ofstream out("hasuri.out");
    in >> N;
    for(int i = 0; i < N; ++i)
    {
        int x, y;
        in >> x >> y;
        if(x == 1)
            add_to_hash_table(y);
        else if(x == 2)
            remove_element_from_hash_table(y);
        else
            out << search(y) << endl;
    }
    return 0;
}