pku2752 Seek the Name, Seek the Fame

Description

    The little cat is so famous, that manycouples tramp over hill and dale to Byteland, and asked the little cat to givenames to their newly-born babies. They seek the name, and at the same time seekthe fame. In order to escape from such boring job, the innovative little catworks out an easy but fantastic algorithm: 
    Step1. Connect the father's name and themother's name, to a new string S. 
    Step2. Find a proper prefix-suffix string ofS (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 towrite 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 describedabove. 
    Restrictions: Only lowercase lettersmay appear in the input. 1 <= Length of S <= 400000. 

Output

    For each test case, output a single linewith integer numbers in increasing order, denoting the possible length of thenew baby's name.

SampleInput

ababcababababcabab

aaaaa

SampleOutput

2 4 9 18

1 2 3 4 5

解题思路:

先计算KMP中next数组的值,则从字符串的长度len开始记录答案,令i=len,每回将i=next[i],直到i=0(0不为答案)。

代码:(请不要直接拷贝哦)

#include <cstdio>
#include <cstring>
char st[400005];
int len,next[400005],ans[400005];
using namespace std;
inline void get_next()//KMP中求next数组的值
{
	next[0]=-1;
	int j=-1,i=0;
	while (i<len)
	  if ((j==-1)||(st[i]==st[j])) next[++i]=++j;
	    else j=next[j]; 
}
int main()
{
	while(~scanf("%s",st))//数据量不定时的另外一种写法,也可以写作"while (scanf("%s",st)!=EOF)"
	{
		len=strlen(st);//求长度
		get_next();
		int i=len,t=0;
		while (i!=0) ans[t++]=i,i=next[i];//记录答案,利用next数组可以节约查询时间
		for (i=t-1;i>0;i--) printf("%d ",ans[i]);
		printf("%d\n",len);
	}	
	return 0;	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值