题目链接:点我
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 aaaaaSample Output
2 4 9 18 1 2 3 4 5题意:
题意:
给定一串字符串,算出可能的前缀,后缀长度,
思路:
KMP算法,算出 next数组即可,
代码:
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<cmath> using namespace std; const int maxn = 4e5+10; char s[maxn]; int nextt[maxn]; int ans[maxn]; void getnextt(int len){ memset(nextt, 0, sizeof(nextt)); nextt[0] = -1; int i = 0, j = -1; while(i < len){ if(j ==- 1 ||s[i] == s[j]){ ++i; ++j; nextt[i] = j; }else j = nextt[j]; } } int main(){ std::ios::sync_with_stdio(false); while(cin>>s){ int len = strlen(s); getnextt(len); int k = 0; for(int i = len ; nextt[i] != -1; i = nextt[i]) ans[++k] = i; for(int i = k ; i > 1; --i) cout<<ans[i]<<' '; cout<<ans[1]<<endl; }return 0; }