Cod sursa(job #768192)

Utilizator igsifvevc avb igsi Data 16 iulie 2012 12:16:19
Problema Hashuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.57 kb
#include<stdio.h>
#include<stdlib.h>

const unsigned int Multiplier = 0x6b43a9b5; /* 2^30 < M < 2^31, M prime*/
struct list{
    unsigned int value;
    struct list *next;
} *hash[13107332];/* 131072 = 2^17 */

int main()
{
    struct list *p, *aux, *prev;
    FILE *in, *out;
    unsigned int op, x, hVal, N;

    in = fopen("hashuri.in", "r");
    out = fopen("hashuri.out", "w");

    fscanf(in, "%u", &N);
    for(; N; --N)
    {
        fscanf(in, "%u %u", &op, &x);
        
        hVal = (x * Multiplier) >> 15;
        for(p = hash[hVal], prev = NULL; p && p->value != x;prev = p, p = p->next);
        
        switch(op)
        {
            case 1:
                if(p == NULL)                
                {
                    aux = malloc(sizeof(struct list));
                    aux->value = x;
                    aux->next = hash[hVal];
                    hash[hVal] = aux;
                }
                break;
            case 2:
                if(p)
                {
                    if(prev)
                    {
                        prev->next = p->next;
                        free(p);
                    }
                    else
                    {
                        hash[hVal] = p->next;
                        free(p);
                    }
                }
                break;
            case 3:
                if(p) fprintf(out, "1\n");
                else fprintf(out, "0\n");
                break;
            default:
                fprintf(stderr, "input error\n");
        }
    }

    fclose(in);
    fclose(out);
    return 0;
}