Cod sursa(job #558956)

Utilizator tm_raduToma Radu tm_radu Data 17 martie 2011 15:26:11
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <stdio.h>

typedef struct nod {
        int vf;
        nod* next;
} NOD, *PNOD;

PNOD h[200001];
int n, i, j, k;

int HashFunction(int a);
void Add(int i, int j);
void Delete(int i, int j);
int Query(int i, int j);

int main()
{
    freopen("hashuri.in", "r", stdin);
    freopen("hashuri.out", "w", stdout);
    scanf("%d", &n);
    for ( k = 1; k <= n; k++ )
    {
        scanf("%d %d", &i, &j);
        if ( i == 1 ) Add(HashFunction(j), j);
        if ( i == 2 ) Delete(HashFunction(j), j);
        if ( i == 3 ) printf("%d\n", Query(HashFunction(j), j));
    }
    return 0;
}

void Add(int i, int j)
{
     if ( h[i] == NULL )
     {
          h[i] = new NOD;
          h[i]->vf = j;
          h[i]->next = NULL;
          return;
     }
     for ( PNOD q = h[i]; q; q = q->next )
     {
         if ( q->vf == j ) return;
         if ( q->next == NULL )
         {
              q->next = new NOD;
              q->next->vf = j;
              q->next->next = NULL;
         }
     }
}

void Delete(int i, int j)
{
     if ( h[i] == NULL ) return;
     if ( h[i]->vf == j )
     {
          PNOD q = h[i];
          h[i] = h[i]->next;
          delete q;
          return;
     }
     for ( PNOD q = h[i]; q && q->next; q = q->next )
         if ( q->next->vf == j )
         {
              PNOD p = q->next;
              q->next = p->next;
              delete p;
         }
}

int Query(int i, int j)
{
     for ( PNOD q = h[i]; q; q = q->next )
         if (q->vf == j ) return 1;
     return 0;
}

int HashFunction(int a)
{
    return (a%399403 + 2*(a%799003)) % 199999;
}