POJ 1961 Period

来源:互联网 发布:js怎么给input赋值 编辑:程序博客网 时间:2024/06/05 06:24
Period
Time Limit: 3000MS
Memory Limit: 30000KTotal Submissions: 13208
Accepted: 6204

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

3aaa12aabaabaabaab0

Sample Output

Test case #12 23 3Test case #22 26 29 312 4

Source

Southeastern Europe 2004

题目链接  :http://poj.org/problem?id=1961

题目大意  :要求一个字符串的具有周期的前缀子串的串长及周期

题目分析  :这类处理周期串的问题我们通常要用到KMP算法中的一个前缀数组这里记为next数组,当 next[cur] = k 时则表示原字符串str[0...(k-1)] = str[(cur-k)...(cur-1)],且k是str的前缀和str[0...cur-1]的后缀间的最长匹配长度,然后我们枚举原字符串的每个前缀str[0]...str[m-1](2 <= m <= n)由  str[0...next[m]-1] = str[(m - next[m])...(m-1)]可知, 若(m - next[m])是m的约数, 则str[0...(m-next[m]-1)]必然是str的最短重复子串.  公式是大家最不愿看到的,这里举一下样例二的例子加以说明aabaabaabaab. 我们先用模版生成next数组得到的next数组为 -1 0 1 0 1 2 3 4 5 6 7 8 9(下标从0开始)
1.当m=2时,2-next[2] = 1,所以str[0]是其最短重复子串,串长2,周期2
2.当m=3时,3-next[3] = 2,不为3的约数故不存在,以下只举存在的情况
3.当m=6时,6-next[6] = 3,所以str[0...2]是其最短重复子串,串长6,周期2
4.当m=9时,9-next[9] = 3,所以str[0...2]是其最短重复子串,串长9,周期3
5.当m=12时,12-next[12] =3,  所以str[0...2]是其最短重复子串,串长12,周期4
笔者这里在写的时候出现了一点问题,后来发现KMP的模版也有很多种,不同模版的计算方法也是不一样的


#include <cstdio>#include <cstring>int const MAX = 1000000 + 5;int next[MAX];  char str[MAX];int len;void cal() //生成next数组{    next[0] = -1;    int k = -1;    int j = 0;    while(str[j] != '\0')    {        if(k == -1 || str[k] == str[j])        {            k++;            j++;            //若当前的j-k是j的约数且约数大于1则j-k即是当前            //最大前缀周期子串的串长            if(j % (j - k) == 0 && j / (j -k) > 1)                printf("%d %d\n", j, j / (j - k));            next[j] = k;        }        else            k = next[k];    }}int main(){    int T = 1;    while(scanf("%d",&len) != EOF && len)    {        scanf("%s",str);        printf("Test case #%d\n",T++);        cal();        printf("\n");    }}


0 0
原创粉丝点击