Problem 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 A K , that is A concatenated K times, for some string A. Of course, we also want to know the period K. Input 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. 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
题意:给出一个字符串,然你找到所有的前缀是循环串的前缀长度,和对应的循环节的循环次数
总结一下,如果对于next数组中的 i, 符合 i % ( i - next[i] ) == 0 && next[i] != 0 , 则说明字符串0-n-1循环,而且
循环节长度为: i - next[i]
循环次数为: i / ( i - next[i] )
如果要问为什么可以自习用几个栗子,然后啃一啃
或者看这里:
next[i]数组的含义是0-i-1个字符中前next[i]和倒数next[i]是完全相同的,那么如果next[i] < (i-1)/2 (即如果这完全相同的前缀和后缀不重合的话)那么有i-next[i]>(i-1)/2则i不可能有i%[i-next[i]]==0这种情况是不可能有循环串的,因为如果是循环串,公共的前缀和后缀肯定是重合的 下面考虑如果重合的情况,如果重合的话,那么一定有i-next[i]就是最小的循环节长度,自己画个图仔细理解一下 然后就有了上面的结论。还是要理解好next的本质才可以 #include<iostream> #include<cstring> using namespace std; #define M 1000005 int Next[M]; char s[M]; void getnext() { int i=0,j=-1; Next[0]=-1; int len=strlen(s); while(i<len) { if(j==-1||s[i]==s[j]) { i++; j++; Next[i]=j; } else j=Next[j]; } } int main() { int text=0,n; while(scanf("%d",&n)>0&&n) { scanf("%s",s); getnext(); printf("Test case #%d\n",++text); int i,j=0; int len=strlen(s); for(i=1;i<len;i++) { if(Next[i+1]!=0&&(i+1)%(i+1-Next[i+1])==0) { printf("%d %d\n",i+1,(i+1)/(i+1-Next[i+1])); } } printf("\n"); } return 0; }