Pagini recente » Cod sursa (job #2540298) | Cod sursa (job #3359769) | Cod sursa (job #3359774) | Cod sursa (job #3359775) | Cod sursa (job #3359771)
#include <fstream>
#include <vector>
class HashTable
{
private:
int HASH_SIZE;
std::vector<int> head;
struct Node
{
int key;
int next;
};
std::vector<Node> nodes;
std::vector<int> values;
std::vector<int> free_list;
int node_count;
static constexpr int HASH_BITS = 20;
inline int get_hash(int x) const
{
uint32_t h = static_cast<uint32_t>(x) * 2654435769u;
return h >> (32 - HASH_BITS);
}
public:
HashTable(int max_elements = 1000005)
{
HASH_SIZE = 1 << HASH_BITS;
head.assign(HASH_SIZE, -1);
nodes.resize(max_elements);
free_list.reserve(max_elements);
values.resize(max_elements);
node_count = 0;
}
inline int allocate_node()
{
if (!free_list.empty())
{
int recycled_index = free_list.back();
free_list.pop_back();
return recycled_index;
}
return node_count++;
}
void Insert(int x)
{
int h = get_hash(x);
// Înlocuim next_node[i] cu nodes[i].next și keys[i] cu nodes[i].key
for (int i = head[h]; i != -1; i = nodes[i].next)
if (nodes[i].key == x)
{
values[i]++;
return;
}
int new_idx = allocate_node();
nodes[new_idx].key = x;
values[new_idx] = 1;
nodes[new_idx].next = head[h];
head[h] = new_idx;
}
void Delete(int x)
{
int h = get_hash(x);
int prev = -1;
for (int i = head[h]; i != -1; prev = i, i = nodes[i].next)
if (nodes[i].key == x)
{
values[i]--;
if (values[i] == 0)
{
if (prev == -1) head[h] = nodes[i].next;
else nodes[prev].next = nodes[i].next;
free_list.push_back(i);
}
return;
}
}
int Count(int x) const
{
int h = get_hash(x);
for (int i = head[h]; i != -1; i = nodes[i].next)
if (nodes[i].key == x) return values[i];
return 0;
}
bool Find(int x) const
{
return (Count(x) > 0);
}
};
int main()
{
std::ifstream fin("hashuri.in");
std::ofstream fout("hashuri.out");
std::ios_base::sync_with_stdio(false);
fin.tie(NULL);
HashTable A;
int n{}, x{}, y{};
fin >> n;
for(int i{};i<n;i++)
{
fin >> x >> y;
if(x == 1) A.Insert(y);
else if(x == 2) A.Delete(y);
else fout << A.Find(y) << "\n";
}
fin.close();
fout.close();
return 0;
}