[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher H - Seek the Name, Seek the Fame POJ - 2752(kmp的next数组应用)

H - Seek the Name, Seek the Fame POJ - 2752

题目链接:https://vjudge.net/contest/70325#problem/H

题目:

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
题意:给你一个字符串,求出所有前缀后缀相同的长度

思路:一个next数组的应用:整个字符串长度为len时,当i = len时,next[len] =a ,说明整个字符串前a个字符和后a个字符相同,所以a是满足要求的。
当i=next[a]时,next[i]=b,则说明前a个字符的前b个和前a个字符的后b个字符相同,同理整个字符串的后a个的前b个和后b个的字符串相同,则满足整个
字符串的前b个和后b个相同,故b满足,以此类推即可,可用递推求出,可看图发现规律:


// 
// Created by HJYL on 2019/8/15.
//
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long ll;
const int maxn=1e6+10;
char str[maxn];
int nextt[maxn];
void getnextt()
{
    int i=0,j=-1;
    nextt[0]=-1;
    int len=strlen(str);
    while(i<len)
    {
        if(j==-1||str[i]==str[j])
        {
            i++,j++;
            //if(str[i]!=str[j])
            nextt[i]=j;
            // else
            //nextt[i]=nextt[j];
        } else
            j=nextt[j];
    }
}
int main()
{

   // freopen("C:\\Users\\asus567767\\CLionProjects\\untitled\\text","r",stdin);
    while(~scanf("%s",str))
    {
        getnextt();
        int len=strlen(str);
        int a[maxn];
        int pos=0;
        int j=len,b=0;
        for(int i=1;i<=len;i++)
        {
            b=nextt[j];
            if(b>0) {
                a[pos++] = b;
                j = nextt[j];
            }

        }
        for(int i=pos-1;i>=0;i--)
            printf("%d ",a[i]);
        printf("%d\n",len);
    }
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/Vampire6/p/11361367.html