Pagini recente » Cod sursa (job #873137) | Cod sursa (job #1550062) | Cod sursa (job #1602197) | Cod sursa (job #558819) | Cod sursa (job #1228025)
#include <bits/stdc++.h>
using namespace std;
template<class T, class HashFunction = std::hash<T>>
class CuckooHash {
public:
void reHash() {
for(int i = 0; i < 2; ++i)
p[i] = 2 * p[i] + 1;
vector<T> aux;
for(int i = 0; i < HashSize; ++i)
if(Table[i] != NULL)
aux.push_back(*Table[i]);
HashSize = p[1] + 1;
Table = vector<T*> (HashSize);
for(auto tmp : aux)
insert(tmp);
}
void insert(T &X) {
int key = hasher(X);
int poz[2] = {0, 0};
for(int i = 0; i < 2; ++i)
poz[i] = key % p[i];
if(Table[poz[0]] == NULL)
Table[poz[0]] = &X;
else if(Table[poz[0]] == NULL)
Table[poz[1]] = &X;
else {
T* tmp = Table[poz[0]];
Table[poz[0]] = &X;
insert(*tmp);
}
KeyCount++;
if(KeyCount * 2 >= HashSize)
reHash();
}
int lookUp(T &X) {
int key = hasher(X);
int poz[2] = {0, 0};
for(int i = 0; i < 2; ++i)
poz[i] = key % p[i];
if(Table[poz[0]] != NULL && *(Table[poz[0]]) == X)
return poz[0];
if(Table[poz[1]] != NULL && *(Table[poz[1]]) == X)
return poz[1];
return -1;
}
void erase(T &X) {
int tmp = lookUp(X);
if(tmp == -1)
return;
Table[tmp] = NULL;
}
CuckooHash(vector<T> A = vector<T>()) {
int sz = A.size();
p[0] = 2 * sz + 1 + rand() % 50;
p[1] = 2 * sz + 51 + rand() % 50;
HashSize = p[1] + 1;
Table = vector<T*>(HashSize);
for(auto tmp : A)
insert(tmp);
KeyCount = sz;
};
private:
HashFunction hasher;
vector<T*> Table;
int p[2];
int HashSize;
int KeyCount;
};
int main() {
ifstream cin("hashuri.in");
ofstream cout("hashuri.out");
srand(time(0));
CuckooHash<int> H;
vector<int> all;
int OpCount; cin >> OpCount;
for(int i = 0; i < OpCount; ++i) {
int Type, X; cin >> Type >> X;
all.push_back(X);
if(Type == 1)
H.insert(X);
else if(Type == 2)
H.erase(X);
else cout << (H.lookUp(X) != -1) << "\n";
}
}