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

【hdu1251-统计难题】Trie

时间:2016-07-19 22:00:01      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

【hdu1251-统计难题】Trie

标签:

原文地址:http://www.cnblogs.com/KonjakJuruo/p/5686407.html

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