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

字典树(tire树)

时间:2014-12-12 23:36:15      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   on   

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树)

标签:style   blog   http   io   ar   color   os   sp   on   

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

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