#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 strings.
The algorithm used to search for a string in this database is very primitive: it compares 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 is found in the database, the algorithm stops.
By analyzing this algorithm, we find that the number of steps needed to find in the database equals the number of strings compared with , plus the sum of the lengths of the common prefixes between and all strings that were compared with it.
There are 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 , the number of strings in the database.
The next 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 , the number of query strings.
The next 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 of the data, , all strings have length , 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 , 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 comparisons, and each of the remaining five strings requires comparisons, so there are comparisons in total.
To find the string majmun, we perform comparisons in total. For the first word, we make successful comparisons, but the last comparison determines that the string majmunica is longer than majmun. For the second string, we also make 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 points.
Translated by ChatGPT 5