KMP + seek equal prefix---POJ seek the Name, seek the Fame

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.