POJ1961 Period
Period
Time Limit: 3000MS | Memory Limit: 30000K | |
Total Submissions: 18405 | Accepted: 8920 |
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.
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
3 aaa 12 aabaabaabaab 0
Sample Output
Test case #1 2 2 3 3 Test case #2 2 2 6 2 9 3 12 4
Source
【题解】
如果一个字符串S是由一个字符串T重复K次形成的,则称T是S的循环元。使K最大的字符串T称为S的最小循环元,此时的K称为最大循环次数。
现在给定一个长度为N的字符串S,对S的每一个前缀S[1~i],如果它的最大循环次数大于1,则输出该前缀的最小循环元长度和最大循环次数。
当i-next[i]能整除i时,S[1~i-next[i]]就是S[1~i]的最小循环元。它的最大循环次数就是i/(i-next[i])。
进一步地,如果i-next[next[i]]能整除i,那么S[1~i-next[next[i]]]就是S[1~i]的次小循环元。
以此类推我们还可以找出S[1~i]所有可能的循环元。
现在给定一个长度为N的字符串S,对S的每一个前缀S[1~i],如果它的最大循环次数大于1,则输出该前缀的最小循环元长度和最大循环次数。
当i-next[i]能整除i时,S[1~i-next[i]]就是S[1~i]的最小循环元。它的最大循环次数就是i/(i-next[i])。
进一步地,如果i-next[next[i]]能整除i,那么S[1~i-next[next[i]]]就是S[1~i]的次小循环元。
以此类推我们还可以找出S[1~i]所有可能的循环元。
——by李煜东
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 7 inline void read(int &x) 8 { 9 x = 0;char ch = getchar(), c = ch; 10 while(ch < '0' || ch > '9')c = ch, ch = getchar(); 11 while(ch <= '9' && ch >= '0')x = x * 10 + ch - '0', ch = getchar(); 12 if(c == '-')x = -x; 13 } 14 15 const int MAXN = 2000000 + 10; 16 17 char s[MAXN]; 18 int n,lens,next[MAXN]; 19 20 void make_next() 21 { 22 memset(next, 0, sizeof(next)); 23 next[0] = -1; 24 for(int i = 1, j = -1; i < lens; ++ i) 25 { 26 while(j >= 0 && s[j+1] != s[i]) j = next[j]; 27 if(s[j+1] == s[i]) ++ j; 28 next[i] = j; 29 } 30 for(register int i = 0;i < lens;++ i) ++next[i]; 31 } 32 33 int cnt; 34 35 int main() 36 { 37 while(scanf("%d", &lens) != EOF && lens) 38 { 39 ++cnt; 40 scanf("%s", s); 41 printf("Test case #%d\n", cnt); 42 make_next();register int lenp; 43 for(register int i = 2;i <= lens;++ i) 44 { 45 lenp = next[i - 1]; 46 if((lenp << 1) >= i && i % (i - lenp) == 0) 47 printf("%d %d\n", i, i/(i - lenp)); 48 } 49 putchar('\n'); 50 } 51 return 0; 52 ;}