Guest

trie

By: a guest on Sep 29th, 2010  |  syntax: C++  |  size: 1.19 KB  |  hits: 115  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. #include <cstdio>
  2. #include <cstring>
  3.  
  4. const int first = 20;
  5. int counter;
  6.  
  7. typedef struct node {
  8.  struct node *adj[255];
  9.  bool end;
  10. }Node;
  11.  
  12. void addWord (Node *root, char *word) {
  13.  Node *vertex = root;
  14.  for( int i = 0; word[i]; i++ ) {
  15.   if( vertex->adj[word[i] - first] == NULL )
  16.     vertex->adj[word[i] - first] = new Node;
  17.   vertex = vertex->adj[word[i] - first];
  18.  }
  19.  vertex->end = true;
  20.  counter++;
  21. }
  22.  
  23. int findWord (Node *root, char *word) {
  24.  Node *vertex = root;
  25.  for( int i = 0; word[i]; i++ ) {
  26.   if( vertex->adj[word[i] - first] == NULL) return -1;
  27.   vertex = vertex->adj[word[i] - first];
  28.  }
  29.  if( vertex->end == false ) return -1;
  30.  else return 1;
  31. }
  32.  
  33. void initRoot (Node *root) {
  34.  for( int i = 0; i < 30; i++ ) root->adj[i] = NULL;
  35.  root->end = false;
  36. }
  37.  
  38. int main () {
  39.  char word[1024];
  40.  Node trie;
  41.  FILE *wordlist = fopen ("wordlist.in","r");
  42.  initRoot (&trie);
  43.  printf ("Creating database...\n");
  44.  while( fgets (word,1024,wordlist) ) addWord (&trie,word);
  45.  printf ("%i words added!\n\n", counter);
  46.  printf ("Word to find: ");
  47.  fgets (word,1024,stdin);
  48.  if( findWord (&trie,word) < 0 ) printf ("Word not found\n");
  49.  else printf ("Word found\n");
  50.  return 0;
  51. }