HDU[1358] Period 【KMP+循环节】

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 A^K , 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

题目大意:

 给定一个长度为N的字符串S,对S的每一个前缀S[1~i],如果它是由某一循环节构成,且循环次数大于1,则求出符合条件的最大的循环次数。

分析:

这里有一个引理:

S[1~i] 具有长度为len<i 的循环节的充要条件是 len 能整除 i 并且 S[len+1~i] = S[1~i-len] 。

根据引理,对字符串S自匹配求出 next 数组,当 i-next[i] 能整除 i 时,S[1~i-next[i]] 就是 S[1~i] 的最小循环节,它的最大循环次数就是 i/(i-next[i]) 。

另:

1. 当 i%(i-next[i]) != 0 时,i-next[i] 仍然是 S[1~i] 的最小循环节,只是最后会剩余一个循环节的部分。

2. 如果 i-next[next[i]] 能整除 i ,那么 S[1~i-next[next[i]]] 就是 S[1~i] 的次小循环节,依次类推。

具体解释见代码。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
const int maxn = 1000000 + 5;

char a[maxn];
int nxt[maxn];
int n;

//KMP计算字符串自身的next数组
void cal_nxt(){
    nxt[1]=0;
    for(int i=2,j=0;i<=n;i++){
        while(j>0&&a[i]!=a[j+1])  j=nxt[j];
        if(a[i]==a[j+1])  j++;
        nxt[i]=j;
    }
}

int main() {
    int cas=0;
    while(scanf("%d",&n)&&n){
        cas++;
        scanf("%s",a+1);
        cal_nxt();
        printf("Test case #%d\n",cas);
        int len;
        for(int i=2;i<=n;i++){
            len=i-nxt[i];//最小循环节长度
            if(i%len==0&&i/len>1){
                printf("%d %d\n",i,i/len);
            }
        }
        printf("\n");
    }
    return 0;
}
发布了30 篇原创文章 · 获赞 5 · 访问量 900

猜你喜欢

转载自blog.csdn.net/qq_42840665/article/details/104129139
今日推荐