字典树

今天刚开始学习字典树,我的第一篇随笔。

字典树,又称单词查找树,Trie树,是一种树形结构,典型应用是用于统计,排序和保存大量的字符串,所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来节约存储空间,最大限度的减少无谓的字符串比较,查询效率比哈希表高。

 

以HDU1251为例    time:125MS,memory:44032K

HDU1251
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<stdlib.h>
 5 using namespace std;
 6 typedef struct node
 7 {
 8     struct node *next[26];
 9     int cnt;//cnt记录个数它之后有几个分支; 
10 }trie;//定义字典树 
11 trie *root;//根节点 
12 void init()//根节点初始化 
13 {
14     int i; 
15     root=(trie*)malloc(sizeof(trie));   
16     for(i=0;i<26;i++)   
17         root->next[i]=0;   
18     root->cnt=2; 
19 }
20 void insert(char *s)//插入新节点 
21 {
22     trie *newnode,*p;//p为当前节点 
23     p=root;
24     int i=0;
25     while(s[i])
26     {
27         int k=s[i++]-'a';//k表示下一个节点的序号 
28         if(p->next[k]){p=p->next[k];p->cnt++;}//若下一个节点不为空,继续访问下一个节点,分支数+1 
29         else//若下一个节点为空,新开节点,分支数=1 
30         {
31             newnode=(trie *)malloc(sizeof(trie));//开内存 
32             for(int j=0;j<26;j++)newnode->next[j]=0;
33             p->next[k]=newnode;
34             p=newnode;
35             p->cnt=1;
36         }    
37     }
38 }
39 int find(char *s)
40 {
41     int i=0;
42     trie *p;
43     p=root;
44     while(s[i])
45     {
46         int k=s[i++]-'a';
47         if(p->next[k])p=p->next[k];//若下一个节点不为空,继续访问下一个节点 
48         else return 0;    
49     }
50     return p->cnt;
51 }
52 int main()
53 {
54     char s[11];
55     int i;
56     //freopen("int.txt","r",stdin);
57     init();
58     while(gets(s)&&strcmp(s,"")!=0)
59     {
60         insert(s);    
61     }
62     while(scanf("%s",s)!=EOF)
63     {
64         int ans=find(s);
65         printf("%d\n",ans);    
66     }
67     return 0;
68 }
posted @ 2012-05-12 16:15  To be an ACMan  Views(299)  Comments(0)    收藏  举报