Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <Windows.h>
- #include <vector>
- using namespace std;
- struct Node
- {
- vector<Node*> children;
- vector<size_t> keys;
- char symbol = '+';
- };
- class TrieTree
- {
- Node* root;
- void addMethod(Node* node, const string& word, const size_t& id, const size_t& key) {
- if (id >= word.size())
- return;
- for (size_t j = 0; j < node->children.size(); j++)
- if (node->children[j]->symbol == word[id])
- {
- node->children[j]->keys.push_back(key);
- addMethod(node->children[j], word, id + 1, key);
- return;
- }
- Node* tmp = new Node;
- tmp->symbol = word[id];
- tmp->keys.push_back(key);
- node->children.push_back(tmp);
- addMethod(tmp, word, id + 1, key);
- };
- void removeMethod(Node* node,const size_t& key) {
- for (size_t i = 0; i < node->children.size(); i++)
- {
- for (size_t j = 0; j < node->children[i]->keys.size(); j++)
- {
- if (node->children[i]->keys[j] == key)
- {
- removeMethod(node->children[i], key);
- if (node->children[i]->keys.size() != 1)
- node->children[i]->keys.erase(node->children[i]->keys.begin() + j);
- else
- node->children.erase(node->children.begin() + i);
- return;
- }
- }
- }
- };
- void getByKeyMethod(Node* node, string& word, const size_t& key)
- {
- for (size_t i = 0; i < node->children.size(); i++)
- {
- for (size_t j = 0; j < node->children[i]->keys.size(); j++)
- {
- if (node->children[i]->keys[j] == key)
- {
- word += node->children[i]->symbol;
- getByKeyMethod(node->children[i], word, key);
- return;
- }
- }
- }
- }
- public:
- TrieTree()
- {
- root = new Node;
- root->symbol = '-';
- }
- void add(const string& word, const size_t& key)
- {
- addMethod(root, word,0, key);
- }
- void remove(const size_t& key)
- {
- removeMethod(root,key);
- }
- string getByKey(const size_t& key)
- {
- string word;
- getByKeyMethod(root, word, key);
- return word;
- }
- };
- int main()
- {
- SetConsoleCP(1251);
- SetConsoleOutputCP(1251);
- TrieTree a;
- a.add("бобёр", 1);
- a.add("лань", 2);
- a.add("бобровый", 3);
- a.add("боб", 4);
- a.add("красный", 5);
- a.add("краснознамённый", 6);
- cout << endl << "Before: " << endl;
- for (size_t i = 1; i < 7; i++)
- {
- cout << i << "] " << a.getByKey(i) << endl;
- }
- a.remove(4);
- a.remove(6);
- cout << endl << "After: " << endl;
- for (size_t i = 1; i < 7; i++)
- {
- cout << i << "] " << a.getByKey(i) << endl;
- }
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement