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

    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

    本题非常的巧妙

    我们先利用nxt[n]就是最长的那个 然后不断查找nxt[nxt[n]]

    直到为0我们就可以将所有的前后缀全部求出

    然后倒序输出即可

    #include<cstdio>
    #include<string.h>
    using namespace std;
    char s[400005];
    int nxt[400005];
    int n;
    void get_nxt()
    {
        int i=0;
        int k=-1;
        nxt[0]=-1;
        while(i<n)
        {
            if(k==-1||s[i]==s[k])
            {
                i++;
                k++;
                nxt[i]=k;
            }
            else
            {
                k=nxt[k];
            }
        }
        return;
    }
    int ans[400005];
    int main()
    {
        while(~scanf("%s",s))
        {
            n=strlen(s);
            get_nxt();
            int cnt=0;
            ans[++cnt]=n;
            int x=n;
            while(x)
            {
                x=nxt[x];
                if(x!=0)
                {
                    ans[++cnt]=x;
                }
            }
            for(int i=cnt;i>=1;i--)
            {
                printf("%d%s",ans[i],i==1?"
    ":" ");
            }
        }
        return 0;
    }
    
  • 相关阅读:
    NumPy使用图解教程
    Pytorch 网络结构可视化
    OpenCV基于字节指针进行高效像素遍历
    scrapy工具创建爬虫工程
    网络爬虫基本概念与Scrapy工具包使用
    CentOS 7命令行安装GNOME桌面
    sicily 1154. Easy sort (tree sort& merge sort)
    全连通图求最小生成树边权之积(邻接矩阵/prim/kruskal)
    sicily 1024. Magic Island
    写在Web考试后的一点小总结
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852212.html
Copyright © 2011-2022 走看看