• 【KMP】Period


    KMP算法

    Next[]函数深入理解,Next[]当前字符前匹配字符数,串长n-Next[i]=串内循环子串的长度p。

    本题求子循环串内循环节数。

    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
     
     1 #include<iostream>
     2 #include<stdio.h>
     3 using namespace std;
     4 
     5 char s[1000001];
     6 int Next[1000001];
     7 
     8 void getNext(int n){
     9     int i=0,j=-1;
    10     Next[0]=-1;
    11     while(i<n){
    12         if(j==-1||s[i]==s[j]){
    13             i++;j++;
    14             Next[i]=j;
    15         }
    16         else j=Next[j];
    17     }
    18 }
    19 
    20 int main()
    21 {
    22     int n,k,t=1,p;
    23     //freopen("pe.txt","r",stdin);
    24     while(cin>>n&&n>1&&n<1000001){
    25         cin>>s;
    26         getNext(n);
    27         cout<<"Test case #"<<t++<<endl;
    28         for(k=2;k<=n;k++){
    29             p=k-Next[k];        //循环节的长度
    30             if(k%p==0&&k/p>1)
    31                 cout<<k<<' '<<k/p<<endl;    //若字符串由循环节构成,第k个字母前完整循环节数
    32         }
    33         cout<<endl;
    34     }
    35     return 0;
    36 }
  • 相关阅读:
    map内置函数、lambda表达式、快捷生成想要的列表、filter内置函数
    python生成随机验证码
    Redis数据库之概念与创建服务
    JavaScript中的类
    python之with的使用
    PHP变量名区分大小写,函数名不区分大小写
    php curl基本操作
    PHP生成随机字符串包括大小写字母
    PHP多例模式
    一个关于动态编译时 Evidence的问题
  • 原文地址:https://www.cnblogs.com/Locked-J/p/4293043.html
Copyright © 2020-2023  润新知