Period
Statement
For each prefix of a given string S with N characters (each character has
an ASCII code between 97 and 126, inclusive), determine whether the prefix is
a periodic string. That is, for each i (2 ≤ i ≤ N), find the largest K >
1 (if one exists) such that the prefix of S with length i can be written
as A^K — the string A concatenated K times, for some string A. Report
the period K for every such prefix.
Input / Output
The input file consists of several test cases. Each test case consists of two
lines: the first contains N, the size of the string S; the second
contains the string S itself. The input ends with a line containing the
single number 0.
For each test case, output "Test case #" followed by the (1-based) test case
number on its own line. Then, for each prefix length i that has a period
K > 1, output i and K separated by a single space, with prefix lengths
in increasing order. Print a blank line after each test case.
Constraints
- 2 ≤ N ≤ 1,000,000
- Each character of
Shas ASCII code in [97, 126]
Example
Input:
3
aaa
12
aabaabaabaab
0
Output:
Test case #1
2 2
3 3
Test case #2
2 2
6 2
9 3
12 4
Solution idea
This is the classic "prefix function" / KMP-failure-function periodicity
problem. Compute the prefix function π[i] of S in O(N) with the standard
KMP preprocessing. For a prefix of length i, the smallest period is
i - π[i], and that prefix is periodic (has a period strictly greater than
1 that evenly divides i) exactly when i - π[i] divides i and
i / (i - π[i]) > 1. Iterating i from 2 to N and applying this check
turns the whole problem into a single linear pass over the prefix-function
array, which is necessary given N up to one million and multiple test
cases per input file.