Skip to content

Instantly share code, notes, and snippets.

@lectricas
Created March 30, 2021 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lectricas/08562b963155d56eb04625fa61f68e66 to your computer and use it in GitHub Desktop.
Save lectricas/08562b963155d56eb04625fa61f68e66 to your computer and use it in GitHub Desktop.
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include <vector>
using namespace std;
#define p 10
#define s 2654435769
#define mod 4294967296
class IntHashMap {
const int m = pow(2, p);
class Node {
public:
Node(const int key, const int value, Node *next, Node *prev) {
this->key = key;
this->value = value;
this->next = next;
this->prev = prev;
}
int value;
int key;
Node *next;
Node *prev;
};
vector<Node *> arr;
public:
IntHashMap() {
cout << m;
arr = vector<Node *>(m);
};
public:
void put(const int key, const int value) {
int bucket = getBucket(key % m);
Node *n = new Node(key, value, nullptr, nullptr);
if (arr[bucket] == nullptr) {
arr[bucket] = n;
} else {
Node *current = arr[bucket];
while (current != nullptr) {
if (current->key == key) {
current->value = value;
return;
}
current = current->next;
}
arr[bucket]->prev = n;
n->next = arr[bucket];
arr[bucket] = n;
}
}
public:
int get(const int key) {
int bucket = getBucket(key % m);
Node *current = arr[bucket];
while (current != nullptr) {
if (current->key == key) {
return current->value;
}
current = current->next;
}
throw "None";
}
public:
int remove(const int key) {
int bucket = getBucket(key % m);
Node *current = arr[bucket];
while (current != nullptr) {
if (current->key == key) {
int value = current->value;
if (current->prev == nullptr) {
arr[bucket] = current->next;
return value;
}
if (current->next != nullptr) {
current->next->prev = current->prev;
}
if (current->prev != nullptr) {
current->prev->next = current->next;
}
return value;
}
current = current->next;
}
throw "None";
}
private:
int getBucket(int h) {
int rem = h * s % mod;
return rem >> (32 - p);
}
};
int main() {
IntHashMap *map = new IntHashMap();
int n;
cin >> n;
std::cin.ignore();
for (int i = 0; i < n; i++) {
std::string line, command;
getline(std::cin, line);
istringstream iss(line);
iss >> command;
try {
int key;
iss >> key;
if (command == "get") {
cout << map->get(key) << "\n";
} else if (command == "delete") {
cout << map->remove(key) << "\n";
} else if (command == "put") {
int value;
iss >> value;
map->put(key, value);
}
} catch (const char *msg) {
std::cout << msg << "\n";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment