Cod sursa(job #1224048)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 29 august 2014 15:50:08
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.64 kb
#include <cstdio>
#include <cstring>
#include <cassert>

#include <algorithm>
#include <vector>

using namespace std;

class Reader {
  public:
    Reader(FILE *_stream, const int _size = (1 << 16)):
      size(_size),
      pointer(0),
      buffer(new char[_size]),
      stream(_stream) {
        assert(fread(buffer, 1, size, stream) != 0);
    }

    template<class IntType>
    IntType NextInt() {
        IntType value = 0;
        bool negative = false;
        while ((Current() < '0' || Current() > '9') && Current() != '-')
            NextPosition();
        if (Current() == '-') {
            negative = true;
            NextPosition();
        }
        while(Current() >= '0' && Current() <= '9') {
            value = value * 10 + Current() - '0';
            NextPosition();
        }
        if (negative)
            value = -value;
        return value;
    }

    Reader &operator>>(int &value) {
        value = NextInt<int>();
        return *this;
    }

  private:
    int size, pointer;
    char *buffer;
    FILE *stream;

    char Current() const {
        return buffer[pointer];
    }

    void NextPosition() {
        if(++pointer == size) {
            assert(fread(buffer, 1, size, stream) != 0);
            pointer = 0;
        }
    }
};

class Hash {
  public:
    Hash() {
        memset(data, EMPTY, sizeof(data));
    }

    void Insert(const int value) {
        for (int i = value % MOD; ; i = (i + 1) % MOD) {
            if (data[i] == EMPTY || data[i] == TOMBSTONE) {
                data[i] = value;
                return;
            }
        }
    }

    void Erase(const int value) {
        for (int i = value % MOD; data[i] != EMPTY; i = (i + 1) % MOD) {
            if (data[i] == value) {
                data[i] = TOMBSTONE;
                return;
            }
        }
    }

    bool Find(const int value) const {
        for (int i = value % MOD; data[i] != EMPTY; i = (i + 1) % MOD)
            if (data[i] == value)
                return true;
        return false;
    }

  private:
    static const int MOD = 1 << 21;
    static const int EMPTY = -1;
    static const int TOMBSTONE = -2;

    int data[MOD];
};

Hash H;

int main() {
    assert(freopen("hashuri.in", "r", stdin));
    assert(freopen("hashuri.out", "w", stdout));
    Reader in = Reader(stdin);
    int q; in >> q;
    for (; q > 0; --q) {
        int type, value;
        in >> type >> value;
        if (type == 1)
            H.Insert(value);
        if (type == 2)
            H.Erase(value);
        if (type == 3)
            printf("%d\n", H.Find(value));
    }
    return 0;
}