Advertisement
Josif_tepe

Untitled

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