Cod sursa(job #2216876)

Utilizator Horia14Horia Banciu Horia14 Data 28 iunie 2018 11:24:55
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include<cstdio>
#define MOD 666013
using namespace std;

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

node* Hash[MOD];

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

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

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

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

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);
        if(op == 1) {
            if(!searchKey(x))
                insertKey(x);
        } else if(op == 2) {
            if(searchKey(x))
                deleteKey(x);
        } else fprintf(fout,"%d\n",searchKey(x));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}