lelouche29

trie

Sep 6th, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include<bits/stdc++.h>
  3. #define hashmap unordered_map<char,node*>
  4. using namespace std;
  5.  
  6. class node{
  7.    public:
  8.     char data;
  9.     hashmap h;
  10.     bool isTerminal;
  11.     node(char d){
  12.         data=d;
  13.         isTerminal=false;
  14.     }
  15. };
  16.  
  17. class trie{
  18.     node *root;
  19.     public:
  20.         trie(){
  21.             root=new node('\0');
  22.         }
  23.  
  24.         //inserting values into trie
  25.         void insert(string word){
  26.             node *temp=root;
  27.             int n=word.length();
  28.             for(int i=0; i<n; i++){
  29.                 char ch=word[i];
  30.                 if(temp->h[ch]==0){
  31.                     node *child=new node(ch);
  32.                     temp->h[ch]=child;
  33.                     temp=child;
  34.                 }
  35.                 else{
  36.                     temp=temp->h[ch];
  37.                 }
  38.             }
  39.             temp->isTerminal=true;
  40.         }
  41.  
  42.         //searching for a word in trie
  43.         bool search(string word){
  44.             node *temp=root;
  45.             int n=word.length();
  46.             for(int i=0; i<n; i++){
  47.                 char ch=word[i];
  48.                 if(temp->h.count(ch))
  49.                     temp=temp->h[ch];
  50.                 else
  51.                     return false;
  52.             }
  53.             return temp->isTerminal;
  54.         }
  55. };
  56.  
  57. int main() {
  58.     int t;
  59.     cin>>t;
  60.     while(t--){
  61.         int n; cin>>n;
  62.         string s[n];
  63.         for(int i=0; i<n; i++){
  64.             cin>>s[i];
  65.         }
  66.  
  67.         trie t;
  68.         for(int i=0; i<n; i++){
  69.             t.insert(s[i]);
  70.         }
  71.         string word;
  72.         cin>>word;
  73.  
  74.         if(t.search(word)) cout<<1<<endl;
  75.         else cout<<0<<endl;
  76.     }
  77.    
  78. }
Advertisement
Add Comment
Please, Sign In to add comment