HDU 2846 Repository

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

对于每个单词都从头到尾分成多个词记录进字典树里,注意判断单词内重复。

#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
const int maxn = 500005;
int T, n, tot;
char s[100];

struct tire
{
    int num[26];
    int now, sum;
    int operator[](int &x){ return num[x]; }
    void insert(int x, int y){ num[x] = y; }
    void clear(){ now = 0; sum = 0; memset(num, 0, sizeof(num)); };
}f[maxn];

int main()
{
    scanf("%d", &n);
    for (int i = tot = 0; i < n; i++)
    {
        scanf("%s", s);
        for (int j = 0; s[j]; j++)
        {
            for (int k = j, a = 0; s[k]; k++)
            {
                int b = s[k] - 'a';
                if (!f[a][b])
                {
                    f[a].insert(b, ++tot);
                    f[tot].clear();
                }
                a = f[a][b];
                if (f[a].now != i + 1) f[a].sum++;
                f[a].now = i + 1;
            }
        }
    }
    scanf("%d", &n);
    while (n--)
    {
        scanf("%s", s);
        int j = 0;
        for (int i = 0; s[i]; i++)
        {
            int k = s[i] - 'a';
            j = f[j][k];
            if (!j) break;
        }
        printf("%d\n", f[j].sum);
    }
    return 0;
}


你可能感兴趣的:(HDU,字典树)