【hdu1251-统计难题】Trie

http://acm.hust.edu.cn/vjudge/problem/16379

题意:给定多个单词,多次询问符合某前缀的单词有多少个。

题解:tire。数组开了5*10^6才A,不然就RE。

 

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cstring>
 4 #include<iostream>
 5 #include<queue>
 6 using namespace std;
 7 
 8 char s[1001];
 9 int num;
10 struct node{
11     int son[30];
12     int cnt;
13 }a[500001];
14 
15 void clear(int x)
16 {
17     a[x].cnt=0;
18     memset(a[x].son,0,sizeof(a[x].son));
19 }
20 
21 void trie(char *c)
22 {
23     int l=strlen(c);
24     int x=0;
25     for(int i=0;i<l;i++)
26     {
27         int t=c[i]-'a'+1;
28         if(!a[x].son[t])
29         {
30             num++;
31             clear(num);
32             a[x].son[t]=num;
33         }
34         x=a[x].son[t];
35         a[x].cnt++;
36     }
37 }
38 
39 int find(char *c)
40 {
41     int l=strlen(c);
42     int x=0;
43     for(int i=0;i<l;i++)
44     {
45         int t=c[i]-'a'+1;
46         if(!a[x].son[t]) return 0;
47         else x=a[x].son[t];
48     }
49     return a[x].cnt;
50 }
51 
52 int main()
53 {
54     freopen("a.in","r",stdin);
55     freopen("a.out","w",stdout);
56     num=0;
57     clear(0);
58     while(1)
59     {
60         // scanf("%s",s);
61         gets(s);
62         if(strlen(s)==0) break;
63         trie(s);
64     }        
65     while(scanf("%s",s)!=EOF)
66     {
67         printf("%d\n",find(s));
68     }
69     return 0;
70 }

 

posted @ 2016-07-19 21:53  拦路雨偏似雪花  阅读(232)  评论(0编辑  收藏  举报