Cod sursa(job #1784969)

Utilizator Eugen01Vasilescu Eugen Eugen01 Data 20 octombrie 2016 18:29:34
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <stdio.h>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int v) : val(v), next(NULL) {}
};

class unord_map {
private:
    ListNode **mymap;
    size_t buckets;
    int hasher(const int &key) const;
public:
    unord_map();
    void insert(const int &key);
    void erase(const int &key);
    int find(const int &key) const;
};

int unord_map::hasher(const int &key) const {
    return (key % buckets);
}

unord_map::unord_map() {
    buckets = 666013;
    mymap = new ListNode*[buckets];
    for (int i = 0; i < buckets; i ++)
        mymap[i] = NULL;
}

void unord_map::insert(const int &key) {
    if (find(key))
        return;
    ListNode *t = new ListNode(key);
    t->next = mymap[hasher(key)];
    mymap[hasher(key)] = t;
}

void unord_map::erase(const int &key) {
    if (!find(key))
        return;

    ListNode *aux = mymap[hasher(key)];

    if (aux && aux->val == key)
        mymap[hasher(key)] = mymap[hasher(key)]->next;

    while (aux && aux->next) {
        if (aux->next->val == key) {
            ListNode *t = aux->next;
            aux->next = aux->next->next;
            delete(t);
            break;
        }
        aux = aux->next;
    }
}

int unord_map::find(const int &key) const {
    if (mymap[hasher(key)] == NULL)
        return 0;

    ListNode *t = mymap[hasher(key)];
    while (t)
        if (t->val == key)
            return 1;

    return 0;
}

int main()
{
    freopen("hashuri.in", "r", stdin);
	freopen("hashuri.out", "w", stdout);

	unord_map mine;
	int n, op, nr;
	scanf("%d", &n);

	for (int i = 0; i < n; i ++) {
        scanf("%d %d", &op, &nr);
        if (op == 1)
            mine.insert(nr);
        else if (op == 2)
            mine.erase(nr);
        else printf("%d\n", mine.find(nr));
	}

    return 0;
}