首页 > 其他 > 详细

字典树(tire树)

时间:2014-12-12 23:35:05      阅读:421      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 
 5 using namespace std;
 6 
 7 struct node
 8 {
 9     int next[26];
10     int cnt;
11     void init()
12     {
13         cnt=0;
14         memset(next,-1,sizeof(next));
15     }
16 }T[1000000];
17 
18 int le;  //第几个字典序
19 
20 void insert(char *s)
21 {
22     int i=0,p=0;
23     while(s[i])
24     {
25         int x=s[i]-a;
26         if(T[p].next[x]==-1)
27         {
28             T[le].init(); 
29             T[p].next[x] = le++;
30         }
31         p=T[p].next[x];
32         T[p].cnt++;
33         i++;
34     }
35 }
36 void query(char *s)
37 {
38     int i=0,p=0;
39     while(s[i])
40     {
41         int x=s[i]-a;
42         if(T[p].next[x]==-1)
43         {
44             puts("0");
45             return ;
46         }
47         p=T[p].next[x];
48         i++;
49     }
50     printf("%d\n",T[p].cnt);
51 }
52 int main()
53 {
54     int n,m;
55     char str[20];
56     scanf("%d",&n);
57     le=1;
58     T[0].init();
59     while(n--) {
60         scanf("%s",str);
61         insert(str);
62     }
63     scanf("%d",&m);
64     while(m--) {
65         scanf("%s",str);
66         query(str);
67     }
68 }
代码君

 

字典树(tire树)

原文:http://www.cnblogs.com/usedrosee/p/4160657.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!