HDU-1358 Period
参考自:
https://blog.csdn.net/qq_41061455/article/details/80370359 HDU-1358 Period 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.
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 Input
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
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 Input
3 aaa 12 aabaabaabaab 0Sample Output
Test case #1 2 2 3 3 Test case #2 2 2 6 2 9 3 12 4
题意:求每一个前缀的最短循环节
分析:本题主要考察了对Next[]数组的理解,可以认为读进来的串本身既是搜索串又是模式串,for( i=1 to i=n) 每一个i-next[i]就是一个基本循环单元长度,那么只要i!=j,那么
这个循环长度就是我们要的答案之一,而当前这个基本循环单元长度出现的次数就是i/(i-next[i])。
AC代码:
1 #include <iostream> 2 #include <cstdio> 3 4 using namespace std; 5 6 int n; 7 char T[1000005]; 8 int Next[1000005]; 9 10 void get_next() 11 { 12 int i = 0, j = -1; 13 Next[0] = -1; 14 while (i < n) 15 { 16 if (j == -1 || T[i] == T[j]) 17 { 18 Next[++i] = ++j; 19 } 20 else 21 j = Next[j]; 22 } 23 } 24 int main() 25 { 26 int kase = 0; 27 while (~scanf("%d", &n)) 28 { 29 if (n == 0) 30 break; 31 scanf("%s", T); 32 get_next(); 33 printf("Test case #%d\n", ++kase); 34 for (int i = 1; i <= n; i++) 35 { 36 int j = i - Next[i]; 37 if (j != i && i % j == 0) 38 { 39 printf("%d %d\n", i, i / j); 40 } 41 } 42 printf("\n"); 43 } 44 return 0; 45 }

更多精彩