Cod sursa(job #1245710)

Utilizator crucerucalinCalin-Cristian Cruceru crucerucalin Data 19 octombrie 2014 21:03:19
Problema Hashuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <forward_list>


class MySet
{
public:
    MySet(int size);

    void add(int value);
    bool contains(int value) const;
    void remove(int value);

private:
    std::size_t hash(int value) const;

    int size_;
    std::vector< std::forward_list<int> > ht_;
};

MySet::MySet(int size)
    : size_(size)
{
    ht_.reserve(size);
}

void MySet::add(int value)
{
    if (contains(value))
        return;

    ht_[hash(value)].push_front(value);
}

bool MySet::contains(int value) const
{
    const std::forward_list<int> &curr_list = ht_[hash(value)];

    for (auto &i : curr_list) {
        if (i == value)
            return true;
    }

    return false;
}

void MySet::remove(int value)
{
    ht_[hash(value)].remove(value);
}

std::size_t MySet::hash(int value) const
{
    value *= 357913941;
    value ^= value << 24;
    value += ~357913941;
    value ^= value >> 31;
    value ^= value << 31;

    return value % size_;
}


int main()
{
    std::ifstream fin("hashuri.in");
    std::ofstream fout("hashuri.out");

    int N;
    fin >> N;

    MySet set(N);
    for (; N; --N) {
        int type;
        long long nr;

        fin >> type >> nr;

        if (type == 1)
            set.add(nr);
        else if (type == 2 && set.contains(nr))
            set.remove(nr);
        else if (type == 3)
            fout << (set.contains(nr) ? "1\n" : "0\n");
    }

    fin.close();
    fout.close();

    return 0;
}