Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <utility>
- #include <vector>
- const int kHashParam = 17;
- const int kModParam = 1000000007;
- int Hash(const std::string& value) {
- int result = 0;
- for (const char c : value) {
- result = (result * kHashParam + c) % kModParam;
- }
- return result;
- }
- struct Node {
- std::string Value;
- Node* Next;
- };
- class HashTable {
- public:
- HashTable() : table(20, nullptr) {}
- ~HashTable() {/*TODO: clear*/}
- bool Has(const std::string& value) const {
- const int hash = Hash(value) % table.size();
- for (Node* p = table[hash]; p != nullptr; p = p->Next) {
- if (p->Value == value) return true;
- }
- return false;
- }
- bool Add(const std::string& value) {
- const int hash = Hash(value) % table.size();
- for (Node* p = table[hash]; p != nullptr; p = p->Next) {
- if (p->Value == value) return false;
- }
- table[hash] = new Node{value, table[hash]};
- return true;
- }
- bool Remove(const std::string& value) {
- const int hash = Hash(value) % table.size();
- Node* p = table[hash];
- if (p == nullptr) return false;
- if (p->Value == value) {
- table[hash] = p->Next;
- delete p;
- return true;
- }
- for (; p->Next != nullptr; p = p->Next) {
- if (p->Next->Value == value) {
- Node* tmp = p->Next;
- p->Next = p->Next->Next;
- delete tmp;
- return true;
- }
- }
- return false;
- }
- private:
- std::vector<Node*> table;
- };
- int main() {
- HashTable t;
- char command = 0;
- std::string value;
- while (std::cin >> command >> value) {
- if (command == '?') {
- std::cout << (t.Has(value) ? "OK" : "FAIL") << std::endl;
- } else if (command == '+') {
- std::cout << (t.Add(value) ? "OK" : "FAIL") << std::endl;
- } else if (command == '-') {
- std::cout << (t.Remove(value) ? "OK" : "FAIL") << std::endl;
- }
- }
- return 0;
- }
- #include <unordered_set>
- int main1() {
- std::unordered_set<std::string> t;
- // В t будет использована std::hash<std::string>, имеющая реализацию в std.
- char command = 0;
- std::string value;
- while (std::cin >> command >> value) {
- if (command == '?') {
- // std::cout << (t.Has(value) ? "OK" : "FAIL") << std::endl;
- } else if (command == '+') {
- // std::cout << (t.Add(value) ? "OK" : "FAIL") << std::endl;
- } else if (command == '-') {
- // std::cout << (t.Remove(value) ? "OK" : "FAIL") << std::endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement