String Hashing
Time limit2sMemory limit512 MB
Count valid strings of any length over ASCII 32 to 126 whose base-31 polynomial hash equals a given string's hash, modulo 1e9+7.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Combinatorics
- Solved
- No attempts yet
Problem
String hashing turns an arbitrary string into a single number. For a string of length , define its hash as
where is the ASCII code of the -th character and means 31 multiplied by itself times. The computation uses big integer arithmetic, so it never overflows.
Here are a few strings and their hashes.
- "ab" (, ASCII codes 97 98), hash
- "Hi!" (, ASCII codes 72 105 33), hash
- "IJ!" (, ASCII codes 73 74 33), hash
Different strings sometimes share a hash, as the second and third strings do.
A string is valid if the ASCII code of every one of its characters is between 32 and 126, inclusive.
Count the valid strings whose hash equals the hash of a given string.
Input
The input has several lines. Each line describes one string as a sequence of space separated integers in the format
is the length of the string () and is the ASCII code of the -th character ().
A line with marks the end of the input and is not processed.
Output
For each string, print on one line the number of valid strings whose hash equals its hash, modulo . The count includes the given string itself.
Hint
The hash of "ab" is 3105. Two other valid strings have that hash, "bC" (ASCII 98 67) and "c$" (ASCII 99 36), so the answer is 3 including "ab" itself. The string with ASCII codes 100 5 also hashes to 3105, but it is not valid because 5 is below 32.
The hash of "Hi!" is 72480, and 12 valid strings have that hash.
The hash of the string made of three spaces is 31776, and no other valid string has that hash.