hdu 2846 Repository (字典树)

Repository
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 7233    Accepted Submission(s): 2278

Problem Description
When you go shopping, you can search in repository for avalible merchandises by the computers and internet. First you give the search system a name about something, then the system responds with the results. Now you are given a lot merchandise names in repository and some queries, and required to simulate the process.
 
Input
There is only one case. First there is an integer P (1<=P<=10000)representing the number of the merchanidse names in the repository. The next P lines each contain a string (it's length isn't beyond 20,and all the letters are lowercase).Then there is an integer Q(1<=Q<=100000) representing the number of the queries. The next Q lines each contains a string(the same limitation as foregoing descriptions) as the searching condition.
 
Output
For each query, you just output the number of the merchandises, whose names contain the search string as their substrings.
 
Sample Input
20
ad
ae
af
ag
ah
ai
aj
ak
al
ads
add
ade
adf
adg
adh
adi
adj
adk
adl
aes
5
b
a
d
ad
s
 
Sample Output
0
20
11
11
2

 

C/C++:

 1 #include <map>
 2 #include <queue>
 3 #include <cmath>
 4 #include <vector>
 5 #include <string>
 6 #include <cstdio>
 7 #include <cstring>
 8 #include <climits>
 9 #include <iostream>
10 #include <algorithm>
11 #define INF 0x3f3f3f3f
12 using namespace std;
13 const int my_max = 1e6 + 10;
14 
15 struct node
16 {
17     int id, cnt, next[26];
18 }my_node[my_max];
19 int flag = 0;
20 
21 void my_init(int x)
22 {
23     for (int i = 0; i < 26; ++ i)
24         my_node[x].next[i] = -1;
25 }
26 
27 void my_insert(char *s, int len, int x)
28 {
29     int now = 0;
30     for (int i = 0; i < len; ++ i)
31     {
32         if (my_node[now].next[s[i] - 'a'] == -1)
33         {
34             my_node[now].next[s[i] - 'a'] = ++ flag;
35             now = flag;
36             my_init(flag);
37         }
38         else now = my_node[now].next[s[i] - 'a'];
39         if (my_node[now].id != x) my_node[now].cnt ++;
40         my_node[now].id = x;
41     }
42 }
43 
44 int my_find(char *s)
45 {
46     int now = 0, len = strlen(s);
47     for (int i = 0; i < len; ++ i)
48     {
49         if (my_node[now].next[s[i] - 'a'] == -1) return 0;
50         now = my_node[now].next[s[i] - 'a'];
51     }
52     return my_node[now].cnt;
53 }
54 
55 int main()
56 {
57     int n, len;
58     scanf("%d", &n);
59     char s[25];
60     my_init(0);
61     while (n --)
62     {
63         scanf("%s", s);
64         len = strlen(s);
65         for (int i = 0; i < len; ++ i)
66             my_insert(s + i, len - i, n + 1);
67     }
68     scanf("%d", &n);
69     while (n --)
70     {
71         scanf("%s", s);
72         printf("%d\n", my_find(s));
73     }
74     return 0;
75 }

 

posted @ 2018-08-21 20:41  GetcharZp  阅读(142)  评论(0编辑  收藏  举报