poj 1204

练习 trie

 1 #include <cstdio>
 2 #include <cstring>
 3 #define maxn 1000000
 4 
 5 struct node {
 6     int v;
 7     char *str;
 8     node *son[26];
 9 }pool[maxn], *tail=pool, *null=pool;
10 struct Trie {
11     node *root;
12     node *newnode( int v, char *value ) {
13         node *nd=++tail;
14         nd->v = v;
15         nd->str = value;
16         for( int s=0; s<26; s++ )
17             nd->son[s] = null;
18         return nd;
19     }
20     void init() {
21         root = newnode(-1,0);
22     }
23     void insert( char *key, char *value ) {
24         node *nd=root;
25         while(1) {
26             if( *key ) {
27                 if( nd->son[*key-'a']==null ) nd->son[*key-'a'] = newnode(*key,0);
28                 nd = nd->son[*key-'a'];
29                 key++;
30             } else {
31                 nd->str = value;
32                 return;
33             }
34         }
35     }
36     const char *find( char *key ) {
37         node *nd=root;
38         while(1) {
39             if( *key ) {
40                 if( nd->son[*key-'a']==null ) return "eh";
41                 nd=nd->son[*key-'a'];
42                 key++;
43             } else {
44                 if( nd->str ) return nd->str;
45                 else return "eh";
46             }
47         }
48     }
49 }T;
50 
51 char line[100];
52 char aa[100010][33], bb[33];
53 
54 int main() {
55     T.init();
56     for( int i=0; ; i++ ) {
57         gets(line);
58         if( strlen(line)==0 ) break;
59         sscanf( line, "%s%s", aa[i], bb );
60         T.insert( bb, aa[i] );
61     }
62     while(1) {
63         if( gets(line)==0  ) break;
64         printf( "%s
", T.find(line) );
65     }
66 
67 }
View Code
原文地址:https://www.cnblogs.com/idy002/p/4331749.html