zoukankan      html  css  js  c++  java
  • poj 2752 Seek the Name, Seek the Fame

    Time Limit: 2000MS   Memory Limit: 65536KB   64bit IO Format: %I64d & %I64u

     Status

    Description

    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

    【解析】
    题目大意:求字符串所有公共前后缀的长度。
    kmp算法
    【code】
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    #define N 400009
    char s[N];
    int next[N],ans[N];
    int l,cnt;
    void getnext()
    {
        l=strlen(s);
        next[0]=-1;
        for(int i=1,j;i<l;i++)
        {
            j=next[i-1];
            while(s[i]!=s[j+1]&&j>=0)
            j=next[j];
            next[i]=s[i]==s[j+1]?j+1:-1;
        }
    }
    int main()
    {
        while(scanf("%s",s)!=EOF)
        {
            getnext();
            cnt=0;
            int ll=l-1;
            cout<<l<<endl;
            cout<<next[l]<<" "<<next[ll]<<endl;
            while(next[ll]!=-1)
            {
                ans[++cnt]=next[ll];
                ll=next[ll];
            }
            for(int i=cnt;i>=1;i--)
            printf("%d ",ans[i]+1);
            printf("%d
    ",l);
        }
        return 0;
    }


  • 相关阅读:
    【原】 OPenCV学习笔记1:imread()
    windows8下:OpenCV2.2.0 +VS2005/2008/2010
    数组指针和指针数组的区别
    虚函数和纯虚函数 覆盖和隐藏
    C/C++文件之eof()
    【转】 CvArr、Mat、CvMat、IplImage、BYTE转换(总结而来)
    HTML 5是如何流行起来的
    Java程序员要注意的10个问题————————好东西就是要拿来分享
    祈福雅安
    对软件工程的思考
  • 原文地址:https://www.cnblogs.com/zzyh/p/6853621.html
Copyright © 2011-2022 走看看