码迷,mamicode.com
首页 > 其他好文 > 详细

字典树模板

时间:2016-10-10 20:31:58      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

 

字典树模板

标签:

原文地址:http://www.cnblogs.com/cshg/p/5946851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!