seek the Name, seek the Fame
problem ' s Link: http://poj.org/problem?id=2752
Mean:
Give you a string to find out how many prefixes in this string are equal to suffixes, and output the lengths of these prefixes in ascending order.
Analyse:
The use of the next array of KMP.
Next[k] (S[0....next[k] and s[k-next[k] ... K] This paragraph is equal, i.e. the longest equal prefix length at the end of K.
Next[k-1] represents the position with the longest suffix with s[0....k] and the longest prefix with S[0...K]. This is where you need to move to next[k-1] after the K-position mismatch.
Specifically, the mismatch is moved to Next[k] or next[k-1], depending on the start number of the next array. If numbering starts at 0, move to Next[k-1]; start numbering from 1, and move to Next[k].
Time complexity:o (N)
Source code:
/*
* This code was made by Crazyacking
* verdict:accepted
* Submission date:2015-07-28-08.55
* time:0ms
* memory:137kb
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#define LL Long Long
#define ULL unsigned long long
using namespace STD;
Const int MAXN=400010;
intN
CharS[MAXN];
int Next[MAXN];
int ans[MAXN];
void GetNext()
{
Next[0]=0;
for(int I=1,k=0;I<N++I)
{
while(s[I]!=S[k]&& k)k=Next[k-1];
if(s[I]==S[k]) ++k;
Next[I]=k;
}
}
int Main()
{
ios_base::Sync_with_stdio(false);
Cin.Tie(0);
while(~scanf('%s ',s))
{
N=strlen(s);
GetNext();
int k=N-1;
int CNT=0;
while(Next[k])
{
ans[CNT++]=Next[k];
k=Next[k-1];
}
ans[CNT++]=N
Sort(ans,ans+CNT);
for(int I=0;I<CNT;++I)
{
printf(I==CNT-1?"%d\ n":"%d",ans[I]);
}
}
return 0;
}
/*
*/
KMP + seek equal prefix---POJ seek the Name, seek the Fame