Description
For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as AK ,that is A concatenated K times, for some string A. Of course, we also want to know the period K.
Input
The input consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S.The second line contains the string S. The input file ends with a line, having the
number zero on it.
Output
For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.
Translation
对于给定长度为n的字符串s,求所有从第1位开始的字符串循环节,输出位置和循环节数量
Analysis
之前做过类似的题,这次换成枚举第i位就可以
论熟练掌握kmp中next数组的用法的重要性
Code
var
s:ansistring;
p:array[0..1000000]of longint;
n,i,ans,count:longint;
procedure init(s:ansistring);
var
i,j:longint;
begin
p[1]:=0;
j:=0;
for i:=2 to length(s) do
begin
while (s[j+1]<>s[i])and(j>0) do j:=p[j];
if (s[j+1]=s[i]) then
inc(j);
p[i]:=j;
end;
end;
begin
readln(n);
while n>0 do
begin
readln(s);
init(s);
inc(count);
writeln('Test case #',count);
for i:=1 to length(s) do
begin
ans:=i div(i-p[i]);
if (ans>1)and(i mod (i-p[i])=0) then
writeln(i,' ',ans);
end;
writeln;
readln(n);
end;
end.