Cod sursa(job #2738495)

Utilizator MateiDorian123Nastase Matei MateiDorian123 Data 5 aprilie 2021 22:26:27
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
ifstream fin("hashuri.in");
ofstream fout("hashuri.out");

const int p = 666013; /// numarul prim de la functia de dispersie
int n; /// numarul de instructiuni

struct nod{
    int x;
    nod* urm;
};

vector<nod*>f; /// tabela de dispersie

inline int hash_fun(int x){
    return x%p;  /// functia de dispersie este x%p
}


void initializare()
{
    for(int i = 0; i < p; i ++)
       f.push_back(NULL);

}

void cmd1(int x){ /// operatia de inserare in hash
    int key = hash_fun(x); /// vedem pe ce pozitie e x
    /// trebuie sa adaugam in f[key] pe x daca acesta nu este deja acolo

    nod *p, *q;
    p = f[key];

    q = new nod;
    q->x = x;
    q->urm = NULL; /// formam noul nod

    if(f[key] == NULL) /// caz particular pentru lista vida
        {f[key] = q;
         return;
        }

    while(p->urm != NULL){
        if(p->x == x) return; /// elementul e deja in hash -> nu mai facem nimic
        p = p->urm;
    }

    if(p->x != x) p->urm = q; /// adaugam nodul la hash
}

void cmd2(int x){ /// operatia de stergere in hash

    int key = hash_fun(x);
    nod *p, *q;
    bool gasit = 0;
    p = f[key];

    if(f[key] == NULL)
        return;

    if(p->x == x){ /// daca elementul pe care dorim sa-l stergem este chiar primul
        f[key] = f[key]->urm;
        delete p;
    }

    for(q = p->urm; q; q = q->urm, p = p->urm)
        if(q->x == x){
        p->urm = q->urm;
        delete q;
    }
}

bool cmd3(int x){ /// verificarea apartenentei
    int key = hash_fun(x);
    nod *p;

    p = f[key];

    while(p != NULL){
        if(p->x == x) return 1;
        p = p->urm;
    }

    return 0;
}

int main()
{   int command, value;

    fin>>n;
    initializare();
    for(int i = 1; i <= n; i++){
        fin>>command>>value;
        if(command == 1)
            cmd1(value);
        else if(command == 2)
            cmd2(value);
        else fout<<cmd3(value)<<"\n";
    }

    fin.close();
    fout.close();

    return 0;
}