zoukankan      html  css  js  c++  java
  • 【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 }
  • 相关阅读:
    jQuery的$.extend
    es5中的严格模式理解(‘use strict’)
    微信小程序制作下拉列表
    微信小程序之路由
    微信小程序自定义弹窗
    微信小程序小总结
    npm link的使用
    vue 全局变量的处理方式
    大屏项目屏幕分辨率适配
    git flow的使用
  • 原文地址:https://www.cnblogs.com/Locked-J/p/4293043.html
Copyright © 2011-2022 走看看