字典树模板
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典树模板相关的知识,希望对你有一定的参考价值。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 6 using namespace std; 7 typedef struct node{ 8 int cnt; 9 node* nex[26]; 10 } Tire; 11 Tire root; 12 void creat_tire(char *str){ 13 14 int len = strlen(str), id; 15 Tire *p = &root, *q; 16 for(int i = 0; i < len; i++){ 17 id = str[i] - ‘a‘; 18 if(p->nex[id] == NULL){ 19 q = new Tire; 20 q->cnt = 1; 21 for(int j = 0; j < 26; j++){ 22 q->nex[j] = NULL; 23 } 24 p->nex[id] = q; 25 p = p->nex[id]; 26 }else { 27 p->nex[id]->cnt++; 28 p = p->nex[id]; 29 } 30 } 31 } 32 int find_tire(char * str){ 33 int len = strlen(str), id; 34 Tire *p = &root; 35 for(int i = 0; i < len; i++){ 36 id = str[i] - ‘a‘; 37 p = p->nex[id]; 38 if(p == NULL) return 0; 39 } 40 return p->cnt; 41 } 42 int main() 43 { 44 char s[15]; 45 for(int i = 0; i < 26; i++) root.nex[i] = NULL; 46 while(gets(s) && s[0] != ‘\0‘){ 47 creat_tire(s); 48 //printf("%s", s); 49 } 50 memset(s, 0, sizeof(s)); 51 while(scanf("%s", s) != EOF){ 52 printf("%d\n", find_tire(s)); 53 } 54 return 0; 55 }
以上是关于字典树模板的主要内容,如果未能解决你的问题,请参考以下文章