Cod sursa(job #2027322)

Utilizator Horia14Horia Banciu Horia14 Data 25 septembrie 2017 21:55:17
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include<cstdio>
#define MOD 666013
using namespace std;

struct node
{
    int val;
    node* next;
};

node* Hash[MOD];

inline int h(int key)
{
    return key % MOD;
}

inline void insertElem(int key)
{
    int val = h(key);
    node* elem = new node;
    elem->val = key;
    elem->next = Hash[val];
    Hash[val] = elem;
}

inline void deleteElem(int key)
{
    int val = h(key);
    node* p, *q;
    if(Hash[val]->val == key)
    {
        q = Hash[val];
        Hash[val] = Hash[val]->next;
        delete q;
    }
    else
    {
        p = Hash[val];
        while(p->next->val != key)
            p = p->next;
        q = p->next;
        p->next = p->next->next;
        delete q;
    }
}

inline bool searchElem(int key)
{
    int val = h(key);
    node* p = Hash[val];
    while(p != NULL && p->val != key)
        p = p->next;
    return (p != NULL) ? 1 : 0;
}

int main()
{
    int n, x, i, op;
    FILE *fin, *fout;
    fin = fopen("hashuri.in","r");
    fout = fopen("hashuri.out","w");
    fscanf(fin,"%d",&n);
    for(i=1; i<=n; i++)
    {
        fscanf(fin,"%d%d",&op,&x);
        switch(op)
        {
            case 1 : if(!searchElem(x)) insertElem(x); break;
            case 2 : if(searchElem(x)) deleteElem(x); break;
            case 3 : fprintf(fout,"%d\n",searchElem(x)); break;
        }
    }
    fclose(fin);
    fclose(fout);
    return 0;
}