题意大概就是给你一个很长的字符串,然后让你找所有满足”前缀=后缀”的长度.
很显然,使用KMP里的求解NEXT数组的思想.
最长的是串的长度,假设为len
这里将next数组做一个变形,让next[i] = next[i+1],那么,第二长的长度就是next[len-1].
通过举例子可以发现,这是个不断迭代的过程,第三长的是next[ next[len-1] -1 ],最后直到next[t]<1时迭代结束.用一个res数组保存每次迭代的结果,最后逆序输出即可.
Description
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
Source
POJ Monthly--2006.01.22,Zeyuan Zhu
#include <iostream>
#include <stdio.h>
#include <iomanip>
//#include <algorithm>
#include <string.h>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <cstdlib>
using namespace std;
int len;
int res[410000], res_num;
int n[410000];
char str[410000];
void Find(char *a)
{
int i = 0;
int k = -1;
int m = len;
n[0] = -1;
while (i < m)
{ // 计算i=1..m-1的next值
while (k >= 0 && a[i] != a[k]) // 求最大首尾子串
k = n[k];
i++;
k++;
n[i] = k; // 不需要优化,就是位置i的首尾子串长度
}
for(int i=0;i<m;i++)
n[i] = n[i+1];
return;
}
int main()
{
while(scanf("%s",&str) != EOF)
{
res_num = 0;
len = strlen(str);
Find(str);
n[len] = len;
int it = len;
while(n[it] > 0)
{
res[res_num++] = n[it];
it = n[it]-1;
}
for(int i=0;i<res_num;i++)
{
printf("%d ",res[res_num-i-1]);
}
printf("\n");
}
return 0;
}