Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6648 Accepted Submission(s): 2456
php
内容转自: http://blog.csdn.net/azheng51714/article/details/7836687node
字典树,又称单词查找树,Trie树,是一种树形结构,典型应用是用于统计,排序和保存大量的字符串,因此常常被搜索引擎系统用于文本词频统计。它的优势是:利用字符串的公共前缀来节约存储空间,最大限度的减小无谓的字符串比较,查询效率比哈希表高。
它有三个基本性质,根节点不包含字符,除根节点外每个节点都只包含一个字符,从根节点到某一节点,路径上通过的字符链接起来,为该节点对应的字符串,每一个节点的全部子节点包含的字符都不相同。算法
题目大意:给定一些单词(按字典序给出), 按字典序输出全部知足条件的单词(条件:该单词由其它两个单词构成)数组
算法描述:先把全部的单词构形成一颗trie图,而后对全部的单词进行枚举,在trie图上面判断一个单词是否由其它两个单词构成,具备的作法是先沿着路径一直走,若是走到某个节点,该节点为一个单词的结尾,那么再对剩余的单词再从trie图的根开始遍历,看是否能和一个单词匹配,若匹配成功则该单词知足要求,不然继续进行匹配...搜索引擎
1 //31MS 5976K 1472 B G++ 2 #include<stdio.h> 3 #include<string.h> 4 struct node{ 5 bool is; 6 node *next[27]; 7 node(){ 8 is=false; 9 memset(next,0,sizeof(next)); 10 } 11 }; 12 char word[50005][27]; 13 void insert(node *root,char s[]) //建立字典树 14 { 15 int i=0; 16 node *p=root; 17 while(s[i]){ 18 int j=s[i++]-'a'; 19 if(p->next[j]==NULL) 20 p->next[j]=new node(); 21 p=p->next[j]; 22 } 23 p->is=true; 24 } 25 int search(node *root,char s[]) 26 { 27 int i=0,len=0,stack[1005]; 28 node *p=root; 29 while(s[i]){ 30 int j=s[i++]-'a'; 31 //if(p-->next[j]==NULL) return 0; 32 p=p->next[j]; 33 if(p->is && s[i]) stack[len++]=i; //记录截点 34 } 35 while(len){ //遍历截点 36 int flag=1; 37 i=stack[--len]; 38 p=root; 39 while(s[i]){ 40 int j=s[i++]-'a'; 41 if(p->next[j]==NULL){ 42 flag=0;break; 43 } 44 p=p->next[j]; 45 } 46 if(flag && p->is) return 1; //知足条件,找到最后,且是一个单词 47 } 48 return 0; 49 } 50 int main(void) 51 { 52 //freopen("C:\\Users\\Administrator\\Desktop\\in.txt","r",stdin); 53 //freopen("C:\\Users\\Administrator\\Desktop\\out.txt","w",stdout); 54 int i=0; 55 node *root=new node(); 56 while(scanf("%s",word[i])!=EOF){ 57 insert(root,word[i]);i++; 58 } 59 for(int j=0;j<i;j++){ 60 if(search(root,word[j])) 61 puts(word[j]); 62 } 63 return 0; 64 }