Pagini recente » Cod sursa (job #1763411) | Cod sursa (job #141694) | Cod sursa (job #2297251) | Cod sursa (job #3294348) | Cod sursa (job #1521927)
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
ifstream f("hashuri.in");
ofstream g("hashuri.out");
class HashTable {
public:
HashTable(int HMAX = 2) {
N = HMAX;
H = new std::vector<int>[N];
cnt = 0;
}
~HashTable() {
if (H != NULL) {
delete[] H;
}
}
void insert(int key) {
static int hash;
if (!find(key)) {
hash = hashFunction(key);
H[hash].push_back(key);
if (++cnt == N) {
rehash();
}
}
}
int find(int key) {
static int hash;
hash = hashFunction(key);
for (std::vector<int>::iterator it = H[hash].begin();
it != H[hash].end(); ++it) {
if (*it == key) {
return 1;
}
}
return 0;
}
void remove(int key) {
static int hash;
hash = hashFunction(key);
for (std::vector<int>::iterator it = H[hash].begin();
it != H[hash].end(); ++it) {
if (*it == key) {
*it = H[hash].back();
H[hash].pop_back();
if (--cnt == N/4) {
rehash();
}
return;
}
}
}
private:
unsigned int cnt, N;
std::vector<int> *H;
unsigned int hashFunction(unsigned int x) {
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = ((x >> 16) ^ x) * 0x45d9f3b;
x = ((x >> 16) ^ x);
return x % N;
}
void rehash() {
int oldN = N;
std::vector<int> *oldH = H;
N = ( cnt == N ? 2*N : N/2);
H = new std::vector<int>[N];
cnt = 0;
for (int i = 0; i < oldN; ++i) {
for (std::vector<int>::iterator it = oldH[i].begin();
it != oldH[i].end(); ++it) {
insert(*it);
}
}
delete[] oldH;
}
};
int main() {
HashTable *H = new HashTable();
int n, type, x;
f >> n;
for (int i = 0; i < n; ++i) {
f >> type >> x;
if (type == 1) {
H->insert(x);
}
if (type == 2) {
H->remove(x);
}
if (type == 3) {
g << H->find(x) << '\n';
}
}
f.close();
g.close();
return 0;
}