Trie dictionary tree template

#include <cstring>  
#include <vector>  
#include <cstdio>  
using namespace std;  
//***********************************************************************************************  
const int maxnode = 4000 * 100 + 10;  
const int sigma_size = 26;  
  
// The alphabet is Trie with all lowercase letters   
struct Trie {  
   int ch[maxnode][sigma_size];  
   int val[maxnode];  
   int sz; // The total number of nodes   
  void clear() { sz = 1 ; memset(ch[ 0 ], 0 , sizeof (ch[ 0 ])); } // Initially there is only one root node   
  int idx( char c) { return c - ' a ' ; } // Number of character c  
  
  // Insert string s, additional information is v. Note that v must be non-zero, because 0 means "this node is not a word node"   
  void insert( const  char *s, int v) {  
     int u = 0 , n = strlen(s);  
     for ( int i = 0 ; i < n; i++ ) {  
       int c = idx(s[i]);  
       if (!ch[u][c]) { // The node does not exist   
        memset(ch[sz], 0 , sizeof (ch[sz] ));  
        val[sz] = 0 ;   // Additional information of the intermediate node is 0   
        ch[u][c] = sz++; // New node   
      }  
      u = ch[u][c]; // go down   
    }  
    val[u] = v; // Additional information for the last character of the string is v   
  }  
  
  // Find the prefix of string s whose length does not exceed len   
  bool find( const  char *s, int len) {  
     int u = 0 ;  
     for ( int i = 0 ; i < len; i++ ) {  
       if (s[i] == ' \0 ' ) break ;  
       int c = idx(s[i]);  
       if (!ch[u][c]) break ;  
      u = ch[u][c];  
       if (val[u] != 0 ) return  true ; // find a prefix   
    }  
     return  false ;  
  }  
};  
  
// ************************************************ **************************************************** ***  
 // The following is a template test   
Trie trie;  
 const  int maxl = 300000 + 10 ; // Maximum length of text string   
const  int maxw = 4000 + 10 ;    // Maximum number of words   
const  int maxwl = 100 + 10 ;    // Maximum length of each word   
char text[maxl], word[maxwl];  
 int main()  
{  
    int n,m;  
    scanf("%d",&n);  
    trie.clear();  
    while(n--){  
        scanf("%s",word);  
        trie.insert(word,1);  
    }  
    scanf("%d",&m);  
    while(m--){  
        scanf("%s",text);  
        int l=strlen(text);  
        if(trie.find(text,l)) printf("\"%s\" in it\n",text);  
        else printf("\"%s\" not in it\n",text);  
    }  
    return 0;  
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324881035&siteId=291194637