Life can be taught, but sometimes simple problems are very well hidden among the difficult ones. Once you identify such a simple problem you are already halfway to solving it, and one big step closer to winning the contest. But be careful -- this is not the simplest problem!
Are you ready for the challenge?
You are given the ordering of the digits used in some hypothetical numeral system, and your task is to transform numbers from various numeral systems to decimal (base 10). Because a number can be read in several ways depending on the base chosen, you must compute the sum of its decimal values over all possible bases.
The input consists of multiple data sets, separated by one or more empty lines.
The first line of each data set defines the ordering of the digits used by the hypothetical numeral system. Every printable ASCII character whose code is greater than 0x20 (space) may be used as a digit, and the characters are listed in order of increasing value (the first character has value 0). Thus the number of defined digits is the largest base possible in that system.
Starting from the second line, each line of the data set is one number written with the digits defined above. For every number, find the sum of its decimal values taken over all valid bases. A base must be at least 2 and strictly greater than the largest digit value that appears in the number.
For example, if the digit ordering is 0123456789, the possible bases are 2 through 10. However, the number 6201 has largest digit 6, so it can only be interpreted in bases 7 through 10.
Whitespace characters at both ends of an input line should be ignored.
For each number in each data set, output on its own line the sum of its decimal values over all valid bases. Separate the output of different data sets with one blank line.