Editorial for LKP '18 Contest 2 P4 - The Zagonetka Machine
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
For the first subtask, brute force suffices. First loop through all prefixes of and check which ones match a suffix of to find all special substrings. Then for each special substring, loop through to count the number of times it occurs.
Time Complexity:
For the last subtask, several approaches work. In this editorial, we will discuss a solution that uses the Knuth-Morris-Pratt or KMP algorithm. First, build the failure function, , of . Suppose we currently have some special substring . We can find the next smallest special substring by using the failure function using which stores the length of the longest prefix of that is also a suffix of . And since is a special substring, it is both a prefix and suffix of and hence, the prefix and suffix of will also be both prefixes and suffixes of . So can be used to recursively generate all special substrings shorter than . We can start this algorithm with since it is always a special substring and we will be able to obtain all special substrings.
Next, we will count all occurrences of special substrings. Observe that each occurrence of the string means that there will be one corresponding occurrence of its prefix of length . We can ignore any prefix of longer than because they aren't special substrings and are irrelevant to the answer. Also, shorter prefixes of will be accounted for by the prefix of length . Therefore we can iterate through all suffixes of from largest to smallest. The number of occurrences of each suffix originally starts at and we use the above observation to count all occurrences that aren't at the end of . Finally, add the occurrences of each special substring to obtain the answer.
Time Complexity:
Comments
Use Suffix Array can also solve it in the time limitaion.