
trie
By: a guest on Sep 29th, 2010 | syntax:
C++ | size: 1.19 KB | hits: 115 | expires: Never
#include <cstdio>
#include <cstring>
const int first = 20;
int counter;
typedef struct node {
struct node *adj[255];
bool end;
}Node;
void addWord (Node *root, char *word) {
Node *vertex = root;
for( int i = 0; word[i]; i++ ) {
if( vertex->adj[word[i] - first] == NULL )
vertex->adj[word[i] - first] = new Node;
vertex = vertex->adj[word[i] - first];
}
vertex->end = true;
counter++;
}
int findWord (Node *root, char *word) {
Node *vertex = root;
for( int i = 0; word[i]; i++ ) {
if( vertex->adj[word[i] - first] == NULL) return -1;
vertex = vertex->adj[word[i] - first];
}
if( vertex->end == false ) return -1;
else return 1;
}
void initRoot (Node *root) {
for( int i = 0; i < 30; i++ ) root->adj[i] = NULL;
root->end = false;
}
int main () {
char word[1024];
Node trie;
FILE *wordlist = fopen ("wordlist.in","r");
initRoot (&trie);
printf ("Creating database...\n");
while( fgets (word,1024,wordlist) ) addWord (&trie,word);
printf ("%i words added!\n\n", counter);
printf ("Word to find: ");
fgets (word,1024,stdin);
if( findWord (&trie,word) < 0 ) printf ("Word not found\n");
else printf ("Word found\n");
return 0;
}