POJ1961

Written by    13:41 October 7, 2015 

POJ1961

Period
Time Limit: 3000MS Memory Limit: 30000K
Total Submissions: 15006 Accepted: 7158

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.

Sample Input

Sample Output

Source

题意

给一个字符串,然后问字符串的不同长度前缀子串最多能有多少个循环体(只有在有大于1个的循环体的时候才输出),比如给出的字符串是 aabaabaabaab,从前缀长度为2的字符串即aa开始,最短的循环体是a,循环次数为两次,那么就输出2 2,前缀长度为3的时候则没有循环体不输出,然后前缀长度为6的时候即aabaab,最短的循环体是aab,循环次数是2,同理前缀长度分别9 和 12的时候输出3 和 4 。

思路

运用KMP算法中的next数组,假设前缀长度长度为i,那么只有在 i % (i – next[i] ) == 0 && i / (i – next[i]) > 1的时候才输出答案。

关于KMP算法,可以参考Matrix67的博客 ,比数据结构课本上讲的确实清楚多了。

这个题用KMP算法确实有点巧,首先KMP算法中的next[i] 表示字符串中的 S[1…next[i]] == S[i-next[i] …i]

当 i % (i – next[i]) == 0 时, 考虑 i == 12,next[i] == 9:

string

(图片来自 AC_Von的博客 )

则 t1+t2+t3 == s1+s2+s3

又因为 s1 == t2 && s2 == t3

所以 s3 == t1

字符串四部分均相等

代码

参考

AC_Von的博客

 

 

Category : acmstudy

Tags :