Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Напиши код на c++ реализация класса «set» с использованием хеш-таблицы. Самостоятельно…

  1. User

    Напиши код на c++ реализация класса «set» с использованием хеш-таблицы. Самостоятельно реализовать основные методы данного класса, не используя стандартный класс set. В реализации должны присутствовать такие методы как: find(), count() .

  2. Assistant

    Вот пример реализации класса "set" с использованием хеш-таблицы:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    class Set {
    private:
        vector<vector<int>> hashTable;
        int size;
    
        int hash(int key) {
            return key % size;
        }
    
    public:
        Set(int size) {
            this->size = size;
            hashTable.resize(size);
        }
    
        void insert(int key) {
            int index = hash(key);
            for (int i = 0; i < hashTable[index].size(); i++) {
                if (hashTable[index][i] == key) {
                    return;
                }
            }
            hashTable[index].push_back(key);
        }
    
        bool find(int key) {
            int index = hash(key);
            for (int i = 0; i < hashTable[index].size(); i++) {
                if (hashTable[index][i] == key) {
                    return true;
                }
            }
            return false;
        }
    
        int count() {
            int count = 0;
            for (int i = 0; i < size; i++) {
                count += hashTable[i].size();
            }
            return count;
        }
    };
    
    int main() {
        Set mySet(10);
        mySet.insert(5);
        mySet.insert(2);
        mySet.insert(8);
        cout << "Set count: " << mySet.count() << endl;
        cout << "Is 2 in the set: " << (mySet.find(2) ? "Yes" : "No") << endl;
        cout << "Is 7 in the set: " << (mySet.find(7) ? "Yes" : "No") << endl;
        return 0;
    }
    

    В данной реализации используется вектор векторов для представления хеш-таблицы. Каждый вектор в этом векторе представляет список значений с одинаковыми хешами. Вектор хеш-таблицы инициализируется заданным размером. Метод hash() используется для вычисления индекса вектора хеш-таблицы для данного ключа. Метод insert() добавляет значение в хеш-таблицу, если оно не существует уже. Метод find() проверяет, существует ли значение в хеш-таблице. Метод count() возвращает количество значений в хеш-таблице.

  3. User

    Напиши код на c++ реализация класса «set» с использованием сбалансированных деревьев. Самостоятельно реализовать основные методы данного класса, не используя стандартный класс set. В реализации должны присутствовать такие методы как: find(), count() .

  4. Assistant

    Вот пример реализации класса "set" с использованием сбалансированных деревьев (конкретно, красно-черных деревьев):

    #include <iostream>
    using namespace std;
    
    enum Color {RED, BLACK};
    
    class Node {
    public:
        int data;
        bool color;
        Node *left, *right, *parent;
    
        Node(int data) {
            this->data = data;
            this->color = RED;
            left = right = parent = nullptr;
        }
    };
    
    class Set {
    private:
        Node* root;
    
        void rotateLeft(Node* node) {
            if (node->right == nullptr)
                return;
    
            Node* rightChild = node->right;
            node->right = rightChild->left;
            if (node->right != nullptr)
                node->right->parent = node;
    
            rightChild->parent = node->parent;
            if (node->parent == nullptr)
                root = rightChild;
            else if (node == node->parent->left)
                node->parent->left = rightChild;
            else
                node->parent->right = rightChild;
    
            rightChild->left = node;
            node->parent = rightChild;
        }
    
        void rotateRight(Node* node) {
            if (node->left == nullptr)
                return;
    
            Node* leftChild = node->left;
            node->left = leftChild->right;
            if (node->left != nullptr)
                node->left->parent = node;
    
            leftChild->parent = node->parent;
            if (node->parent == nullptr)
                root = leftChild;
            else if (node == node->parent->left)
                node->parent->left = leftChild;
            else
                node->parent->right = leftChild;
    
            leftChild->right = node;
            node->parent = leftChild;
        }
    
        void fixInsert(Node* node) {
            while (node != root && node->parent->color == RED) {
                if (node->parent == node->parent->parent->left) {
                    Node* uncle = node->parent->parent->right;
                    if (uncle != nullptr && uncle->color == RED) {
                        node->parent->color = BLACK;
                        uncle->color = BLACK;
                        node->parent->parent->color = RED;
                        node = node->parent->parent;
                    } else {
                        if (node == node->parent->right) {
                            node = node->parent;
                            rotateLeft(node);
                        }
                        node->parent->color = BLACK;
                        node->parent->parent->color = RED;
                        rotateRight(node->parent->parent);
                    }
                } else {
                    Node* uncle = node->parent->parent->left;
                    if (uncle != nullptr && uncle->color == RED) {
                        node->parent->color = BLACK;
                        uncle->color = BLACK;
                        node->parent->parent->color = RED;
                        node = node->parent->parent;
                    } else {
                        if (node == node->parent->left) {
                            node = node->parent;
                            rotateRight(node);
                        }
                        node->parent->color = BLACK;
                        node->parent->parent->color = RED;
                        rotateLeft(node->parent->parent);
                    }
                }
            }
            root->color = BLACK;
        }
    
        Node* findNode(Node* root, int key) {
            if (root == nullptr || root->data == key)
                return root;
    
            if (root->data < key)
                return findNode(root->right, key);
    
            return findNode(root->left, key);
        }
    
        int countNodes(Node* root) {
            if (root == nullptr)
                return 0;
    
            return 1 + countNodes(root->left) + countNodes(root->right);
        }
    
    public:
        Set() {
            root = nullptr;
        }
    
        void insert(int key) {
            Node* node = new Node(key);
            Node* parent = nullptr;
            Node* current = root;
    
            while (current != nullptr) {
                parent = current;
                if (node->data < current->data)
                    current = current->left;
                else if (node->data > current->data)
                    current = current->right;
                else
                    return; // Duplicate keys are not allowed
            }
    
            node->parent = parent;
            if (parent == nullptr)
                root = node;
            else if (node->data < parent->data)
                parent->left = node;
            else
                parent->right = node;
    
            fixInsert(node);
        }
    
        bool find(int key) {
            Node* node = findNode(root, key);
            return node != nullptr;
        }
    
        int count() {
            return countNodes(root);
        }
    };
    
    int main() {
        Set mySet;
        mySet.insert(5);
        mySet.insert(2);
        mySet.insert(8);
        cout << "Set count: " << mySet.count() << endl;
        cout << "Is 2 in the set: " << (mySet.find(2) ? "Yes" : "No") << endl;
        cout << "Is 7 in the set: " << (mySet.find(7) ? "Yes" : "No") << endl;
        return 0;
    }
    

    В данной реализации используется сбалансированное дерево (красно-черное дерево) для хранения значений. Класс "Node" представляет узел дерева с данными, цветом и указателями на левого, правого и родительского узлы. Класс "Set" содержит методы для вставки значений в дерево, поиска значения в дереве и подсчета количества значений в дереве. Методы rotateLeft() и rotateRight() выполняют повороты узлов для поддержания баланса дерева. Метод fixInsert() исправляет возможные нарушения свойств красно-черного дерева после вставки нового узла. Метод findNode() рекурсивно находит узел с заданным ключом в дереве. Метод countNodes() рекурсивно подсчитывает количество узлов в дереве.