Cod sursa(job #2108560)

Utilizator karakter98Irimia Robert karakter98 Data 18 ianuarie 2018 15:30:13
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <stdio.h>
#define MOD 1000000
using namespace std;

typedef struct node
{
    int info;
    node* next;
} node;
node* H[MOD];

void add(int x)
{
    int key = x % MOD;
    node* q = H[key];
    if(H[key] == NULL)
    {
        H[key] = new node;
        H[key]->info = x;
        H[key]->next = NULL;
        return;
    }
    while(q->next)
    {
        if(q->info == x)
            return;
        q = q->next;
    }
    if(q->info != x)
    {
        node *p = new node;
        q->next = p;
        p->info = x;
    }
}

void take(int x)
{
    int key = x % MOD;
    if(H[key] == NULL)
        return;
    if(x == H[key]->info)
    {
        node* aux = H[key];
        H[key] = H[key]->next;
        delete aux;
        return;
    }
    node* prev = H[key];
    node* q = H[key]->next;
    while(q)
    {
        if(q->info == x)
        {
            if(q->next)
            {
                prev->next = q->next;
                delete q;
            }
            else
            {
                prev->next = NULL;
                delete q;
            }
            return;
        }
        q = q->next;
        prev = prev->next;
    }
}

int query(int x)
{
    int key = x % MOD;
    node* q = H[key];
    while(q)
    {
        if(q->info == x)
            return 1;
        q = q->next;
    }
    return 0;
}

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

    return 0;
}