• poj 2752 Seek the Name, Seek the Fame


    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

    找出S的前缀,满足前缀也是S的后缀,要求所有满足的按长度递增输出前缀长度。
    比如说ababcababababcabab,首先本身就是前缀也是后缀,且相同,长度是18,然后根据kmp的Next数组,确立非本串的最长前后缀为ababcabab,长度为9,前缀是往前缩短,后缀是往后缩短,也就是说接下来要找的是Next[9],即[0,9]子串最长相同前后缀,因此这里用递归来倒着找并输出。
    代码:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define MAX 400001
    char str[MAX];
    int Next[MAX],len;
    void findNext() {
        int j = -1,i = 0;
        Next[0] = -1;
        while(i < len) {
            if(j == -1 || str[i] == str[j]) {
                Next[++ i] = ++ j;
            }
            else j = Next[j];
        }
    }
    void print(int k) {
        if(k) {
            print(Next[k]);
            printf("%d ",k);
        }
    }
    int main() {
        while(gets(str)) {
            len = strlen(str);
            findNext();///先确立Next数组
            print(len);
            putchar('
    ');
        }
    }
  • 相关阅读:
    ****阿里云使用+快速运维总结(不断更新)
    Linux 标准目录结构
    linux awk命令
    反射型 DDoS 攻击的原理和防范措施
    容器平台选型的十大模式:Docker、DC/OS、K8S 谁与当先?
    谈谈数据库的跨机房容灾-网易云
    前端 支持 超大上G,多附件上传
    java 支持 超大上G,多附件上传讨论
    java 支持 超大上G,多附件上传分享
    java 支持 超大上G,多附件上传功能
  • 原文地址:https://www.cnblogs.com/8023spz/p/9656225.html
Copyright © 2020-2023  润新知