Cod sursa(job #2081499)

Utilizator Horia14Horia Banciu Horia14 Data 4 decembrie 2017 19:26:59
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include<cstdio>
#define MOD 1390421
using namespace std;

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

node* Hash[MOD];

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

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

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

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

int main() {
    int n, i, op, x;
    FILE *fin, *fout;
    fin = fopen("hashuri.in","r");
    fout = fopen("hashuri.out","w");
    fscanf(fin,"%d",&n);
    for(i = 0; 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;
}