ট্রাই ট্রি ( Trie Tree )
ডাটা স্ট্রাকচার: ট্রাই (প্রিফিক্স ট্রি/রেডিক্স ট্রি)
Trie (Keyword Tree) -- H1 , H2
Zobayer blog -- using static array
Quora Tutorial
Implemention 01:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | #include <bits/stdc++.h> using namespace std; #define INF 1<<30 #define MAX 100005 #define FASTIO ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); typedef long long ll; const int ALPHABET = 26; #define scale(x) (x - 'a') struct TrieTree { struct TrieTree *children[ALPHABET]; bool isEndOfWord; }; struct TrieTree *getNode() { struct TrieTree *Node = new TrieTree; Node->isEndOfWord = false; for(int i = 0; i < ALPHABET; i++) Node->children[i] = NULL; return Node; } void insert(struct TrieTree *root, string s) { struct TrieTree *curr = root; for(int i = 0; i < s.size(); i++){ int idx = scale(s[i]); if(!curr->children[idx]) curr->children[idx] = getNode(); curr = curr->children[idx]; } // mark last node as leaf curr->isEndOfWord = true; } bool search(struct TrieTree *root, string s) { struct TrieTree *curr = root; for(int i = 0; i < s.size(); i++){ int idx = scale(s[i]); if(!curr->children[idx]) return false; curr = curr->children[idx]; } return (curr != NULL && curr ->isEndOfWord); } bool isEmpty(TrieTree* root) { for(int i = 0; i < ALPHABET; i++) if(root->children[i]) return false; return true; } TrieTree* Remove(TrieTree* root, string s, int depth = 0) { if(!root)return NULL; if(depth == s.size()){ if(root->isEndOfWord) root->isEndOfWord = false; if(isEmpty(root)){ delete(root); root = NULL; } return root; } int idx = scale(s[depth]); root->children[idx] = Remove(root->children[idx], s, depth+1); if(isEmpty(root) && root->isEndOfWord == false){ delete(root); root = NULL; } return root; } int main() { //FASTIO /*// //double start_time = clock(); #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); freopen("error.txt", "w", stderr); #endif //*/ string str[] = { "the", "a", "there", "answer", "any", "by", "bye", "their", "hero", "heroplane"}; int n = sizeof(str)/sizeof(str[0]); struct TrieTree *root = getNode(); for(int i = 0; i < n; i++) insert(root, str[i]); // Search for different keys search(root, "the")? cout << "FOUND!\n" : cout << "NOT FOUND\n"; search(root, "these")? cout << "FOUND!\n" : cout << "NOT FOUND\n"; Remove(root, "heroplane"); // Remove(root, "hero"); search(root, "hero") ? cout << "FOUND!\n" : cout << "NOT FOUND\n"; //double end_time = clock(); //printf( "Time = %lf ms\n", ( (end_time - start_time) / CLOCKS_PER_SEC)*1000); return 0; } |