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;
    }


  • 相关阅读:
    Java_jdbc 基础笔记之六 数据库连接 (PreparedStatement)
    Java_jdbc 基础笔记之五 数据库连接 (ResultSet)
    如何在Windows Server 2008服务器中把Tomcat启动程序添加到服务中
    WebService(axis2),整合springmvc
    shiro学习
    mysql中的concat函数,concat_ws函数,concat_group函数之间的区别
    mysql几种关联的区别
    wzyxidian Scanner 与 Readable 的read()方法
    LINQ系列:LINQ to SQL Take/Skip
    LINQ系列:LINQ to SQL Concat/Union
  • 原文地址:https://www.cnblogs.com/zzyh/p/6853621.html
Copyright © 2011-2022 走看看