字典树模板

trie的原理是利用字符串集合中字符串的公共前缀来降低时间开销以达到提高效率的目的。
它具有以下性质:

1,根结点不包含任何字符信息;

2,如果字符的种数为n,则每个结点的出度为n;

3,查找,插入复杂度为O(n),n为字符串长度。

举例:

查找一个字符串时,我们只需从根结点按字符串中字符出现顺序依次往下走。如果到最后字符串结束时,对应的结点标记为红色,则该字符串存在;

否则不存在。
插入时也只需从根结点往下遍历,碰到已存在的字符结点就往下遍历,否则,建立新结点;最后标记最后一个字符的结点为红色即可。
同时我们看到,如果字符的种类为n,则需要结点的个数为n级数。
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1251

模板:

 1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 struct Tree {
5 Tree * ch[26];
6 int n , flag ;
7 } root ;
8 char word[15] ;
9 void init ( Tree * t ) {
10 int i ;
11 for ( i = 0 ; i < 26 ; i ++ )
12 t -> ch[i] = NULL ;
13 t -> n = t -> flag = 0 ;
14 }
15 void insert ( struct Tree * t , char * in ) {
16 if ( * in ) {
17 if ( t -> ch[ * in - 'a' ] == NULL ) {
18 t -> ch[ * in - 'a' ] = ( struct Tree * ) malloc ( sizeof ( struct Tree ) ) ;
19 init ( t -> ch[ * in - 'a' ] ) ;
20 }
21 t -> ch[ * in - 'a' ] -> n ++ ;
22 insert ( t -> ch[ * in - 'a' ] , in + 1 ) ;
23 }
24 else t -> flag = 1 ;
25 }
26 int find ( struct Tree * t , char * in ) {
27 if ( t -> ch[ * in - 'a' ] != NULL ) {
28 if ( * ( in + 1 ) == '\0' )
29 return t -> ch[ * in - 'a' ] -> n ;
30 return find ( t -> ch[ * in - 'a' ] , in + 1 ) ;
31 }
32 else return 0 ;
33 }
34
35 int main () {
36 while ( gets( word ) ) {
37 if ( strlen ( word ) == 0 )
38 break ;
39 insert ( &root , word ) ;
40 }
41 while ( scanf ( "%s" , word ) != EOF ){
42 printf ( "%d\n" , find ( & root , word ) );
43 }
44 return 0 ;
45 }

  插入和查找可以模板。

posted @ 2011-07-29 15:01  贺佐安  阅读(315)  评论(0)    收藏  举报