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.
Medium7Dynamic programmingCombinatoricsNo attempts yetTime limit2sMemory limit512 MBString hashing turns an arbitrary string into a single number. For a string S of length N, define its hash as
S[0]×31N−1+S[1]×31N−2+⋯+S[N−2]×31+S[N−1]
where S[i] is the ASCII code of the i-th character and 31k means 31 multiplied by itself k times. The computation uses big integer arithmetic, so it never overflows.
Here are a few strings and their hashes.
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.
The input has several lines. Each line describes one string as a sequence of space separated integers in the format
NS[0]S[1]⋯S[N−1]
N is the length of the string (1≤N≤1000) and S[i] is the ASCII code of the i-th character (32≤S[i]≤126).
A line with N=0 marks the end of the input and is not processed.
For each string, print on one line the number of valid strings whose hash equals its hash, modulo 1000000007. The count includes the given string itself.
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.