Cod sursa(job #768161)

Utilizator igsifvevc avb igsi Data 16 iulie 2012 11:24:04
Problema Hashuri Scor 70
Compilator c Status done
Runda Arhiva educationala Marime 1.73 kb
#include<stdio.h>
#include<stdlib.h>

#define H(X) (((X) * Multiplier) >> (32 - hashSize))

const unsigned int Multiplier = 0x6b43a9b5; /* 2^30 < M < 2^31, M prime*/
const unsigned int hashSize = 17; /* 2^17 */

struct list{
    unsigned int value;
    struct list *next, *prev;
} *hash[131072];/* 131072 = 2^17 */

unsigned int N;

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

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

    fscanf(in, "%u", &N);
    for(; N; --N)
    {
        fscanf(in, "%u %u", &op, &x);
        
        hVal = H(x);
        for(p = hash[hVal]; p && p->value != x; p = p->next);
        
        switch(op)
        {
            case 1:
                if(p == NULL)                
                {
                    p = malloc(sizeof(struct list));
                    p->value = x;
                    p->next = hash[hVal];
                    p->prev = NULL;
                    if(hash[hVal]) hash[hVal]->prev = p;
                    hash[hVal] = p;
                }
                break;
            case 2:
                if(p)
                    if(p->prev)
                    {
                        aux = p->prev;
                        aux->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;
}