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


  • 相关阅读:
    P1410 子序列
    P1395 会议 (树形dp)
    P2580 于是他错误的点名开始了
    LC1127. 用户购买平台
    LC 1308. Running Total for Different Genders
    P1340 兽径管理 (最小生成树)
    P1330 封锁阳光大学 (二分图染色)
    CF1296F Berland Beauty (Tree, dfs/bfs, LCA)
    顺丰的Cookie条款
    服务器判断客户端的用户名和密码(token的身份验证)
  • 原文地址:https://www.cnblogs.com/zzyh/p/6853621.html
Copyright © 2011-2022 走看看