1. 程式人生 > >HDU-1358 Period

HDU-1358 Period

urn largest number https fir nat namespace seve des

參考自: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
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[]數組的理解,可以認為讀進來的串本身既是搜索串又是模式串,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 }

HDU-1358 Period