Advertisement
Josif_tepe

Untitled

Dec 12th, 2023
640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #include <map>
  5. using namespace std;
  6. const int alphabet_size = 26;
  7. struct node {
  8.     bool is_end_of_word;
  9.     node * children_of_node[alphabet_size];
  10.     node() {
  11.         is_end_of_word = false;
  12.         for(int i = 0; i < alphabet_size; i++) {
  13.             children_of_node[i] = NULL;
  14.         }
  15.     }
  16. };
  17. void insert_word(node * trie, string word) {
  18.     node * tmp = trie;
  19.     for(int i = 0; i < (int) word.size(); i++) {
  20.         int c = word[i] - 'a';
  21.         if(tmp -> children_of_node[i] == NULL) {
  22.             tmp -> children_of_node[i] = new node();
  23.         }
  24.         tmp = tmp -> children_of_node[i];
  25.     }
  26.     tmp -> is_end_of_word = true;
  27. }
  28. bool search_word(node * trie, string word) {
  29.     node * tmp = trie;
  30.     for(int i = 0; i < (int) word.size(); i++) {
  31.         int c = word[i] - 'a';
  32.         if(tmp -> children_of_node[i] == NULL) {
  33.             return false;
  34.         }
  35.         tmp = tmp -> children_of_node[i];
  36.     }
  37.     return tmp -> is_end_of_word;
  38. }
  39. void delete_word(node * trie, string word) {
  40.     node * tmp = trie;
  41.     for(int i = 0; i < (int) word.size(); i++) {
  42.         int c = word[i] - 'a';
  43.         if(tmp -> children_of_node[i] == NULL) {
  44.             return;
  45.         }
  46.         tmp = tmp -> children_of_node[i];
  47.     }
  48.     tmp -> is_end_of_word = false;
  49. }
  50. int main() {
  51.     ios_base::sync_with_stdio(false);
  52.     node * trie = new node();
  53.    
  54.     while(true) {
  55.         string a, b;
  56.         cin >> a >> b;
  57.         if(a == "insert") {
  58.             insert_word(trie, b);
  59.         }
  60.         else if(a == "delete") {
  61.             delete_word(trie, b);
  62.         }
  63.         else {
  64.             cout << search_word(trie, b) << endl;
  65.         }
  66.     }
  67.     return 0;
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement