POJ2752 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:)

找出一个字符串中既是前缀又是后缀的子串的所有长度.

分析

参照jklover的题解。

此题使用hash十分简单,直接枚举每个前缀,与长度相等的后缀比较即可.

时间复杂度:线性。

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#define rg register
#define il inline
#define co const
template<class T>il T read()
{
    rg T data=0;
    rg int w=1;
    rg char ch=getchar();
    while(!isdigit(ch))
    {
        if(ch=='-')
            w=-1;
        ch=getchar();
    }
    while(isdigit(ch))
    {
        data=data*10+ch-'0';
        ch=getchar();
    }
    return data*w;
}
template<class T>il T read(rg T&x)
{
    return x=read<T>();
}
typedef unsigned long long ull;

co int N=4e5+1;
co ull Base=233;
ull Hash[N],Pow[N];
int n;
char s[N];
int ans[N];

ull calchash(int l,int r)
{
    if(l==0)
        return Hash[r];
    return (Hash[r]-Hash[l-1]*Pow[r-l+1]);
}

int main()
{
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    Pow[0]=1;
    for(int i=1;i<N;++i)
        Pow[i]=Pow[i-1]*Base;
    while(~scanf("%s",s))
    {
        n=strlen(s);
        Hash[0]=s[0];
        for(int i=1;i<n;++i)
            Hash[i]=Hash[i-1]*Base+s[i];
        int qlen=0;
        for(int i=0;i<n;++i)
        {
            ull hashpre=calchash(0,n-i-1);
            ull hashsuf=calchash(i,n-1);
            if(hashpre==hashsuf)
                ans[++qlen]=n-i;
        }
        for(int i=qlen;i>=1;--i)
            printf("%d ",ans[i]);
        puts("");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/autoint/p/10326620.html