您的位置:首页 > 其它

Seek the Name, Seek the Fame(KMP算法之next数组的深入理解实例)

2016-01-28 13:17 399 查看
[align=center]Seek the Name, Seek the Fame[/align]
Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 15436Accepted: 7808
DescriptionThe 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 escapefrom 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 stringsof S? (He might thank you by giving your baby a name:)InputThe 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.OutputFor 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
大致题意:给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀。从小到大依次输出这些子串的长度。大致思路:如左图,假设黑色线来代表字符串str,其长度是len,红色线的长度代表next[len],根据next数组定义易得前缀的next[len]长度的子串和后缀next[len]长度的子串完全相同(也就是两条线所对应的位置)。我们再求出next[len]位置处的next值,也就是图中蓝线对应的长度。同样可以得到两个蓝线对应的子串肯定完全相同,又由于第二段蓝线属于左侧红线的后缀,所以又能得到它肯定也是整个字符串的后缀。所以对于这道题,求出len处的next值,并递归的向下求出所有的next值,得到的就是答案。#include<stdio.h>#include<string.h>int next[400005];char str[400005];int sum[400000];void getNext(char *str,int next[]){int k=strlen(str);next[0]=-1;int i=0,j=-1;while (i<k){if (j==-1||str[i]==str[j]){i++;j++;next[i]=j;}elsej=next[j];}}int main(){while (scanf("%s",str)!=EOF){int k=0,i;int len=strlen(str);getNext(str,next);for(i=len;i!=0;){sum[k++]=next[i];i=next[i];}for(i=k-2;i>=0;--i)printf("%d ",sum[i]);printf("%d\n",len);}return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: