#P7937. [COCI 2007/2008 #5] BAZA

[COCI 2007/2008 #5] BAZA

Problem Description

Define the common prefix of two strings as the substring that both strings share starting from the beginning. For example, the common prefix of the string identity and the string idealistic is ide.

A database contains NN strings.

The algorithm used to search for a string WW in this database is very primitive: it compares WW with the strings in the database one by one. For each pair of strings, it compares characters one by one until it finds a mismatching character or reaches the end of one of the strings, and then performs one final comparison to determine whether the two strings have the same length. When WW is found in the database, the algorithm stops.

By analyzing this algorithm, we find that the number of steps needed to find WW in the database equals the number of strings compared with WW, plus the sum of the lengths of the common prefixes between WW and all strings that were compared with it.

There are QQ query strings.

Write a program that computes, for each query string, how many steps the program needs to find this word in the database.

Please note the unusual memory limit for this problem.

Input Format

The first line contains an integer NN, the number of strings in the database.

The next NN lines each contain one string from the database. These strings are given in the order in which the algorithm checks them, and they are all distinct.

The next line contains an integer QQ, the number of query strings.

The next QQ lines each contain one query string.

Output Format

For each query string, output one line with one integer, the number of steps required for the program to find this word in the database.

5
hobotnica
robot
hobi
hobit
robi
4
robi
hobi
hobit
rakija 
12
10
16
7 
8
majmunica
majmun
majka
malina
malinska
malo
maleni
malesnica
3
krampus
malnar
majmun 
8
29
14

Hint

For 100%100\% of the data, 1N,Q3×1041 \le N, Q \le 3 \times 10^4, all strings have length <30< 30, and they contain only lowercase letters.

Explanation for Sample 2:

For Sample 2, the number of steps used to search for the string krampus is 88, because we only need to compare the first character of each string in the database with this string.

When searching for malnar, each of the first three strings requires 33 comparisons, and each of the remaining five strings requires 44 comparisons, so there are 2929 comparisons in total.

To find the string majmun, we perform 1414 comparisons in total. For the first word, we make 66 successful comparisons, but the last comparison determines that the string majmunica is longer than majmun. For the second string, we also make 66 successful comparisons, and in the final comparison we find that the two strings have equal length, so the algorithm stops.

The score for this problem follows the original contest setting, with a full score of 9090 points.

Translated by ChatGPT 5