zoukankan      html  css  js  c++  java
  • kuangbin专题十六 KMP&&扩展KMP POJ2752 Seek the Name, Seek the Fame

    The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm:

    Step1. Connect the father's name and the mother's name, to a new string S.
    Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S).

    Example: Father='ala', Mother='la', we have S = 'ala'+'la' = 'alala'. Potential prefix-suffix strings of S are {'a', 'ala', 'alala'}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:)
    Input
    The input contains a number of test cases. Each test case occupies a single line that contains the string S described above.

    Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.
    Output
    For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby's name.
    Sample Input
    ababcababababcabab
    aaaaa
    
    Sample Output
    2 4 9 18
    1 2 3 4 5


    题目要求既是前缀又是后缀的字符串的长度。 本身的长度肯定符合。然后逆序求得Next[i]即可。再逆序输出。


     1 #include<stdio.h>
     2 #include<string.h>
     3 int Next[400010],n;
     4 char p[400010];
     5 int ans[400010],pos;
     6 
     7 void prekmp() {
     8     n=strlen(p);
     9     int i,j;
    10     j=Next[0]=-1;
    11     i=0;
    12     while(i<n) {
    13         while(j!=-1&&p[i]!=p[j]) j=Next[j];
    14         Next[++i]=++j;
    15     }
    16 }
    17 
    18 int main() {
    19     //freopen("in","r",stdin);
    20     while(~scanf("%s",p)) {
    21         pos=0;
    22         prekmp();
    23         for(int i=n;Next[i]>0;i=Next[i]) {
    24             ans[pos++]=Next[i];
    25         }
    26         for(int i=pos-1;i>=0;i--)
    27             printf("%d ",ans[i]);
    28         printf("%d
    ",n);
    29     }
    30 }




  • 相关阅读:
    Java(八)——面向对象(4)-抽象类与接口
    Java(七)——面向对象(3)-多态
    Java(六)——面向对象(2)-继承
    Java(五)——面向对象(1)-基础
    Java(四)——数组
    Java(三)——流程控制
    Java(二)——Java基础
    易忘小技巧--yum
    网络测速命令--speedtest
    大型网站架构技术读后感
  • 原文地址:https://www.cnblogs.com/ACMerszl/p/10268604.html
Copyright © 2011-2022 走看看