码迷,mamicode.com
首页 > 其他好文 > 详细

poj1961--Period(KMP求一个串的重复子串)

时间:2015-04-08 01:05:57      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Period
Time Limit: 3000MS   Memory Limit: 30000K
Total Submissions: 13949   Accepted: 6601

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

Source

 
题目大意:
给出一个长为N的串S,
求从开头到S[i](2<=i<=N)的子串的最大重复子串,
如果这个子串由n个重复子串组成,
输出 i 和  n。
 
分析:实际上是考察对KMP算法的next数组的理解,
next数组中的k本质上维护了从距离j最近的上一个重复串中与j对应的位置.
如果一个长度L字符串由n个重复子串组成,那最后一个字符的next值为L-L/n.
注意n可以为1.
 
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<string>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 const int maxn = 1000100;
 8 int n;
 9 int Next[maxn];
10 char str[maxn];
11 
12 void KMP(){
13     int j = 0, k = -1;
14     Next[0] = -1;
15     while (str[j]!=\0){
16         if (k == -1 || str[j] == str[k]){
17             k++;
18             j++;
19             if (j % (j - k) == 0 && j / (j - k) > 1)
20                 printf("%d %d\n", j, j / (j - k));
21             Next[j] = k;
22         }
23         else
24             k = Next[k];
25     }
26 }
27 
28 int main()
29 {
30     int iCase = 0;
31     while (scanf("%d", &n) != EOF&&n!=0){
32         iCase++;
33         scanf("%s", &str);
34         printf("Test case #%d\n",iCase);
35         KMP();
36         printf("\n");
37     }
38     return 0;
39 }

 

poj1961--Period(KMP求一个串的重复子串)

标签:

原文地址:http://www.cnblogs.com/lxzd723/p/4401022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!