Advertisement
jeff69

Trie

Oct 11th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int MAX=1e5+9;
  4. string h;
  5. struct trie
  6. {
  7.     trie * child [27];
  8.     bool ischild[27];
  9.     int here=0;
  10.     bool endf=0;
  11. };
  12. trie head;
  13.  
  14. void enter(string &h)
  15. {
  16.     trie * temp= &head;
  17.  
  18.     for( int i=0;i<h.size();i++)
  19.     {
  20.         //cout<<i<<endl;
  21.         if(!temp->ischild[h[i]-'a'])temp->child[h[i]-'a']=new trie;
  22.         temp->ischild[h[i]-'a']=1;
  23.           temp=temp->child[h[i]-'a'];
  24.  
  25.         temp->here++;
  26.         if(i==(int)h.size()-1)temp->endf=1;
  27.     }
  28. }
  29. bool srch(string & h)
  30. {
  31.     trie * temp= &head;
  32.  
  33.     for( int i=0;i<h.size();i++)
  34.     {
  35.        // cout<<i<<endl;
  36.         if(!temp->ischild[h[i]-'a'])return 0;
  37.           temp=temp->child[h[i]-'a'];
  38.  
  39.  
  40.         if(i==(int)h.size()-1)return temp->endf;
  41.     }
  42.  
  43. }
  44. int pref(string &h)
  45. {
  46.   trie * temp= &head;
  47.  
  48.     for( int i=0;i<h.size();i++)
  49.     {
  50.        // cout<<i<<endl;
  51.         if(!temp->ischild[h[i]-'a'])return 0;
  52.           temp=temp->child[h[i]-'a'];
  53.  
  54.  
  55.         if(i==(int)h.size()-1)return temp->here;
  56.     }
  57. }
  58. int main()
  59. {
  60.     for(int i=0;i<5;i++)
  61.     {
  62.         cin>>h;
  63.     enter(h);
  64.     }
  65.     string c;
  66.     cin>>c;
  67.     cout<<pref(c);
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement