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


  • 相关阅读:
    vue echarts 遇到的bug之一 无法渲染的问题
    前端SSR方案调研
    【读书笔记】数据结构与算法js描述-链表实现
    【转发】数组,字符串常用方法
    【转】README.md 语法汇总
    webpack 配置遇到的坑
    原生audio 实现音频播放器功能
    活动抽奖组件设计
    理解vue-loader
    kpi sql 积累
  • 原文地址:https://www.cnblogs.com/zzyh/p/6853621.html
Copyright © 2011-2022 走看看