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
分析:
题意要求我们找出以各个首字符为开头的前缀与尾字符为结尾的后缀相匹配的长度,并且用升序输出。
我们由“Next 数组”的应用知道:Next[i]表示的是第i-1位为截止的重复出现的字符串的长度。那么直接在Next[i+1]这个数就是要求的最长的那个字符串,然后不停地向前回溯,每次回溯就是这个字符串的子字符串(结尾相同)的长度,直到回溯为0截止。
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int Next[4000005];
int ans[4000005];
char a_str[4000005];
int len;
void get_next(){
int j = 0, k = -1;
Next[0] = -1;
while(j < len){
if(k == -1 || a_str[j] == a_str[k]){
k++;
j++;
Next[j] = k;
}
else
k = Next[k];
}
}
int main(){
while(scanf("%s", a_str) != EOF) {
len = strlen(a_str);
get_next();
int k = len;
int j = 0;
while(k != -1){
ans[j++] = k;
k = Next[k];
}
for(int i = j - 2; i >= 0; i--){
(i != 0) ? (printf("%d ", ans[i])) : (printf("%d\n", ans[i]));
}
}
return 0;
}
推荐阅读
-
MongoDB 谨防索引seek的效率问题
-
在Python中操作文件之seek()方法的使用教程
-
file.seek()/tell()-笔记
-
在使用seek()函数时,有时候会报错为 “io.UnsupportedOperation: can't do nonzero cur-relative seeks”,代码如下:
-
php中将指针移动到数据集初始位置的实现代码[mysql_data_seek]
-
kafka调用seek方法后调用subscribe方法报错
-
POJ 2752 Seek the Name, Seek the Fame G++ 哈希未实现 KMP背
-
20201213_133_文件对象常用方法和属性总结_seek()任意位置操作
-
BZOJ 1941: [Sdoi2010]Hide and Seek(k-d Tree)
-
go语言基础 seek光标位置os包的使用