Advertisement
Josif_tepe

Untitled

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