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 }
  • 相关阅读:
    [JXOI2018]游戏
    UltraISO制作启动盘安装CentOS7
    龙芯、鲲鹏、飞腾等国产平台的浏览器
    浏览器相关性能测试网址
    有没有一种组合字体,中文是宋体,英文是times new roman?
    中国航天科工集团第二研究院706所招聘
    华为云
    面试阿里P6难在哪?(面试难点)
    Linux下配置环境变量—— .bashrc 和 /etc/profile
    Linux 内存 占用较高问题排查
  • 原文地址:https://www.cnblogs.com/Locked-J/p/4293043.html
Copyright © 2011-2022 走看看