Joyful KMP
Time limit1sMemory limit1024 MB
Count the lowercase strings that have the same failure function as the given string, and print the K-th one in lexicographic order or OVER.
- Level
Hard8 of 10
- Topics
- String matching, Combinatorics, Greedy
- Solved
- No attempts yet
Problem
Hongjun recently learned the KMP (Knuth-Morris-Pratt) algorithm and is stuck on understanding the failure function. For a string , its failure function consists of values , where is the length of the longest string that is both a proper prefix and a suffix of . If no such string exists, is . For example, the failure function of abcabd is shown in the table below.
To understand the failure function better, Hongjun picked a string and wants to list, in lexicographic order, every string made only of lowercase English letters that has the same failure function. You decide to help him. Write a program that counts the strings with the same failure function as the given string and finds the -th one in lexicographic order.
Input
The first line contains a string of length between 1 and , inclusive. The string consists only of lowercase English letters.
The second line contains a single positive integer ().
Output
On the first line, print the number of lowercase strings that have the same failure function as the input string, modulo . This number can be very large.
On the second line, print the string that comes -th in lexicographic order among those strings. If there are fewer than such strings, print OVER.
Hint
Only strings in which the first and third characters are equal, the second and fourth characters are equal, and the first and second characters differ have the same failure function as abab. So the number of such strings is .
The 100th string in lexicographic order is dzdz.