【题解】HDU-1358 Period

Period (HDU-1358)

题面

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.

输入

The input file 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.

输出

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.

样例输入

1
2
3
4
5
3
aaa
12
aabaabaabaab
0

样例输出

1
2
3
4
5
6
7
8
9
Test case #1
2 2
3 3

Test case #2
2 2
6 2
9 3
12 4

提示

思路

KMP求最小循环节。输出所有可以由循环构成的前缀。

代码

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
char t[mxn];
int nxt[mxn];

void getnxt(char* t, int m)
{
int i = 0, j = -1; nxt[0] = -1;
while (i < m)
{
if (j == -1 || t[i] == t[j]) {
i++, j++;
// if (t[i] == t[j])
// nxt[i] = nxt[j]; // next数组优化
// else
nxt[i] = j;
} else
j = nxt[j];
}
}

int main()
{
int cs=0, m;
while(~scanf("%d", &m) && m)
{
scanf("%s", t);
getnxt(t, m);
printf("Test case #%d\n", ++cs);

for(int i=0; i<=m; i++){
if(nxt[i]>0){
int L = i-nxt[i]; // 最小循环节=原串长度-末位失配,L=len-next[len]
if(i%L == 0)
printf("%d %d\n", i, i/L); // 循环周期T=len/L
}
}
printf("\n");
}
return 0;
}
_/_/_/_/_/ EOF _/_/_/_/_/