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;
    }
    
  • 相关阅读:
    HDU 1269 迷宫城堡 tarjan算法求强连通分量
    hrbust 1721 A + B = 0 map的应用
    关于vis标记
    poj 1703
    poj1961 kmp
    acm poj1260 dp
    矩阵链乘 hrbust 1600
    单源最短路径 hdu 2066
    最小生成树
    多维背包 hrbudt 1335 算法与追MM
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852212.html
Copyright © 2011-2022 走看看