Period
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4485 Accepted Submission(s): 2163Problem DescriptionFor 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.InputThe 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.OutputFor 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 Input3aaa12aabaabaabaab0Sample OutputTest case #12 23 3Test case #22 26 29 312 4
这道KMP入门,主要在于加深next函数的理解,即与自身的匹配。
1 #include<iostream> 2 #include<vector> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <math.h> 7 #include<algorithm> 8 #define ll long long 9 #define eps 1e-8 10 using namespace std; 11 12 int nexts[1000050]; 13 char str[1000050]; 14 15 void pre_nexts(int n)//next函数 16 { 17 memset(nexts,0,sizeof(nexts)); 18 int j = 0,k = -1; 19 nexts[0] = -1; 20 while(str[j]) 21 { 22 if(k == -1 || str[j] == str[k]) nexts[++j] = ++k;//与自身的子串匹配 23 else k = nexts[k];//匹配失败,返回 24 } 25 } 26 void KMP() 27 { 28 int i,t; 29 for(i = 2; str[i-1]; i++) 30 { 31 t = i - nexts[i];//子串长度 32 if(i % t == 0 && i / t > 1) printf("%d %d ",i,i/t);//如果当前位置为一个循环节,則输出 33 } 34 } 35 int main(void) 36 { 37 int n,cnt = 1; 38 while(scanf("%d",&n),n) 39 { 40 scanf("%s",str); 41 pre_nexts(n); 42 printf("Test case #%d ",cnt++); 43 KMP(); 44 printf(" "); 45 } 46 return 0; 47 }