HDU1358 Period —— KMP 最小循环节

题目链接:https://vjudge.net/problem/HDU-1358

 

Period

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9652    Accepted Submission(s): 4633


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 AK , 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
 

 

Recommend
JGShining

 

 

题解:

给出一个字符串s,问字符串s的哪些前缀是循环的(以某个字符串至少循环两次)。

此题需要熟悉kmp的next数组。

1.在get_next函数中,如果当前匹配到前缀i:可知前缀i的最小循环节为i-next[i]。

2.如果循环节不等于前缀i自身,且前缀i的长度能被循环节的长度整除,则符合题目要求,输出答案。

3.详情还是请看代码吧。

 

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <string>
 6 #include <vector>
 7 #include <map>
 8 #include <set>
 9 #include <queue>
10 #include <sstream>
11 #include <algorithm>
12 using namespace std;
13 typedef long long LL;
14 const double eps = 1e-6;
15 const int INF = 2e9;
16 const LL LNF = 9e18;
17 const int MOD = 1e9+7;
18 const int MAXN = 1e6+10;
19 
20 char x[MAXN];
21 int Next[MAXN];
22 
23 void get_next(char x[], int m)
24 {
25     int i, j;
26     j = Next[0] = -1;
27     i = 0;
28     while(i<m)
29     {
30         while(j!=-1 && x[i]!=x[j]) j = Next[j];
31         Next[++i] = ++j;
32         int r = i-Next[i]; //当前前缀的最小循环节
33         if(i!=r && i%r==0)  //最小循环节不等于自己,且除得尽
34             printf("%d %d\n", i, i/(i-Next[i]));
35     }
36 }
37 
38 int main()
39 {
40     int len, kase = 0;
41     while(scanf("%d", &len) && len)
42     {
43         scanf("%s", x);
44         printf("Test case #%d\n", ++kase);
45         get_next(x, len);
46         printf("\n");
47     }
48 }
View Code

 

posted on 2017-11-19 18:15  h_z_cong  阅读(178)  评论(0编辑  收藏  举报

导航