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.
样例输入
13
2aaa
312
4aabaabaabaab
50
样例输出
1Test case #1
22 2
33 3
4
5Test case #2
62 2
76 2
89 3
912 4
提示
无
思路
KMP求最小循环节。输出所有可以由循环构成的前缀。
代码
1char t[mxn];
2int nxt[mxn];
3
4void getnxt(char* t, int m)
5{
6 int i = 0, j = -1; nxt[0] = -1;
7 while (i < m)
8 {
9 if (j == -1 || t[i] == t[j]) {
10 i++, j++;
11 // if (t[i] == t[j])
12 // nxt[i] = nxt[j]; // next数组优化
13 // else
14 nxt[i] = j;
15 } else
16 j = nxt[j];
17 }
18}
19
20int main()
21{
22 int cs=0, m;
23 while(~scanf("%d", &m) && m)
24 {
25 scanf("%s", t);
26 getnxt(t, m);
27 printf("Test case #%d\n", ++cs);
28
29 for(int i=0; i<=m; i++){
30 if(nxt[i]>0){
31 int L = i-nxt[i]; // 最小循环节=原串长度-末位失配,L=len-next[len]
32 if(i%L == 0)
33 printf("%d %d\n", i, i/L); // 循环周期T=len/L
34 }
35 }
36 printf("\n");
37 }
38 return 0;
39}