HDU 2846 Repository

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.

InputThere 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.OutputFor 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


 1 #include <cstdio>
 2 #include <cstring>
 3 using namespace std;
 4 const int N = 1e6 + 5;
 5 int trie[N][26], cnt[N], id[N], L;
 6 
 7 void insertTrie(char s[], int iid)
 8 {
 9     int r = 0, i = 0, j;
10     while(s[i])
11     {
12         j = s[i++] - 'a';
13         if(!trie[r][j])
14             trie[r][j] = L++;
15         r = trie[r][j];
16         if(id[r] != iid) ++cnt[r];
17         id[r] = iid;
18     }
19 }
20 int searchTrie(char s[])
21 {
22     int r = 0, i = 0, j;
23     while(s[i])
24     {
25         j = s[i++] - 'a';
26         if(!trie[r][j])
27             return 0;
28         r = trie[r][j];
29     }
30     return cnt[r];
31 }
32  
33 int main()
34 {
35     L = 1;
36     char s[30];
37     int p, q;
38     scanf("%d", &p);
39     for(int i = 1; i <= p; ++i)
40     {
41         scanf("%s", s); 
42         for(int j = 0; s[j]; ++j)
43             insertTrie(s + j, i);
44     }
45     scanf("%d", &q);
46     while(q--)
47     {
48         scanf("%s", s);
49         printf("%d\n", searchTrie(s));
50     }
51     return 0;
52 }

猜你喜欢

转载自www.cnblogs.com/linda-/p/13383000.html
今日推荐