Pagini recente » Cod sursa (job #2547533) | Cod sursa (job #187059) | Profil andrici_cezar | Cod sursa (job #51889) | Cod sursa (job #2738481)
#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;
}
p->urm = q; /// adaugam nodul la hash
}
void cmd2(int x){ /// operatia de stergere in hash
int key = hash_fun(x);
nod *p;
bool gasit = 0;
p = f[key];
if(p == NULL)
return;
if(p->x == x){ /// daca elementul pe care dorim sa-l stergem este chiar primul
f[key] = f[key]->urm;
delete p;
}
while(p->urm != NULL && !gasit){
if(p->urm->x == x) gasit = 1; /// ne oprim fix inaintea nodul
p = p->urm;
}
if(gasit){
nod *q = p->urm; /// q este elementul pe care vrem sa-l stergem
p->urm = q->urm; /// am scos q din lista
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;
}