Pagini recente » Cod sursa (job #3161326) | Cod sursa (job #1752394) | Cod sursa (job #2456418) | Cod sursa (job #1012864) | Cod sursa (job #2736231)
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
struct Node {
int val;
Node* next;
Node(int x) : val(x), next(nullptr) {}
};
class HashTable {
private:
std::vector<Node*> table;
const unsigned tbl_size_exponent;
unsigned hash(int x)
{
unsigned idx = 1ULL * 459727289478483 * x;
idx >>= (32 - tbl_size_exponent);
return idx;
}
public:
HashTable(unsigned size) : tbl_size_exponent(size) { table.resize( (1<<size) ); }
void Add(int x)
{
unsigned idx = hash(x);
Node* n = new Node(x);
if (table[idx] == nullptr)
{
table[idx] = n;
}
else
{
Node* temp = table[idx];
while (temp->val != x && temp->next != nullptr)
{
temp = temp->next;
}
if (temp->val != x)
temp->next = n;
}
}
bool Check(int x)
{
unsigned idx = hash(x);
Node* temp = table[idx];
while (temp != nullptr)
{
if (temp->val == x)
return 1;
temp = temp->next;
}
return 0;
}
void Delete(int x)
{
unsigned idx = hash(x);
Node** temp = &table[idx];
while (*temp != nullptr)
{
if ((*temp)->val == x)break;
temp = &(*temp)->next;
}
if (*temp == nullptr)return;
Node* del = *temp;
*temp = (*temp)->next;
delete del;
}
};
int main()
{
std::ifstream f("hashuri.in");
std::ofstream g("hashuri.out");
int n;
f >> n;
HashTable h(int(log2(n) + 1));
for (int i = 0; i < n; ++i)
{
int tip, x;
f >> tip >> x;
switch (tip)
{
case 1: h.Add(x); break;
case 2: h.Delete(x); break;
case 3: g << h.Check(x) << '\n'; break;
}
}
}