Cod sursa(job #1492247)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 27 septembrie 2015 14:14:30
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <bits/stdc++.h>

const unsigned Nmax = 1000000;
const unsigned NIL = -1;
const unsigned MASK = (1 << 20);
const unsigned FNV_prime = 16777619;
const unsigned FNV_offset_basis = 2166136261U;
const unsigned BUFFSIZE = 4096;

struct h
{
    unsigned v, next;
};

h l[Nmax];
unsigned lsize;
unsigned h[MASK];
unsigned st[Nmax], s;
char buff[BUFFSIZE];
unsigned ptr = BUFFSIZE;

inline unsigned H(const unsigned &x)
{
    unsigned hsh = FNV_offset_basis;
    hsh = hsh ^ x;
    hsh = hsh * FNV_prime;
    return ( hsh & ( MASK - 1 ) );
}

inline bool hashFind(const unsigned &x)
{
    unsigned i = h[H(x)];

    while ((i != NIL) && (l[i].v != x))
        i = l[i].next;
    return (i != NIL);
}

inline void hashInsert(const unsigned &x)
{
    unsigned p = s ? st[--s] : lsize++;
    unsigned hash = H(x);

    l[p].v = x;
    l[p].next = h[hash];
    h[hash] = p;
}

inline void hashExtract(const unsigned &x)
{
    unsigned hash = H(x);
    unsigned i = h[hash];

    if (l[i].v == x)
        h[hash] = l[i].next;
    else
    {
        while ((l[i].next != NIL) && (l[l[i].next].v != x))
            i = l[i].next;
        if (l[i].next != NIL)
        {
            st[s++] = l[i].next;
            l[i].next = l[l[i].next].next;
        }
    }
}

inline char getChr()
{
    if (ptr == BUFFSIZE)
    {
        fread(buff, 1, BUFFSIZE, stdin);
        ptr = 0;
    }
    return buff[ ptr++ ];
}

inline unsigned readInt()
{
    register unsigned q = 0;
    char c;

    do
    {
        c = getChr();
    } while (!isdigit(c));
    do
    {
        q = (q << 1) + (q << 3) + (c - '0');
        c = getChr();
    } while (isdigit(c));
    return q;
}

int main()
{
    freopen("hashuri.in", "r", stdin);
    freopen("hashuri.out", "w", stdout);
    unsigned testNum;
    char opType;
    unsigned x;

    memset(h, NIL, sizeof(h));

    testNum = readInt();
    for (; testNum; testNum--)
    {
        do
        {
            opType = getChr();
        } while (!isdigit(opType));
        x = readInt();
        if (opType == '1')
            hashInsert(x);
        else if (opType == '2')
            hashExtract(x);
        else
        {
            putchar(hashFind(x) + '0');
            putchar('\n');
        }
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}