Application array of nature Period HDU 1358 KMP next
The meaning of problems
You mean to subject a string, this string is determined prefix string, the string which is the period, the number of output and the length of the prefix string prefix string loop section.
Problem-solving ideas
Ideas Reference: https://www.cnblogs.com/yym2013/p/3586495.html
This question is examined KMP
in the algorithm next
applied an array, we must thoroughly understand next[]
the meaning of the representative of the array in order to resolve this question by it.
Idea is to construct next[]
an array subscript i
, define a variable j = i - next[i]
is next
the difference array corresponding to the superscript and subscript values, if the difference divisible subscript i
, i.e. i%j==0
, the description subscript i
character string before (periodic string length is a i
) an be represented by a periodic out prefix, prefix length for that difference just determined, i.e. j
, the prefix of the number of times of occurrence i/j
. Therefore, the final output and i i/j
can.
Note: This algorithm can not find next is the kind of simplified form.
It should be special treatment next[i] = 0
or next = -1
to ignore.
Code
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<stack>
#include<queue>
#include<map>
using namespace std;
const int MAXN=1e6+7;
char s[MAXN];
int nx[MAXN], n;
void get_next()
{
int j=0, k=-1, len=n;
nx[0]=-1;
while(j<len)
{
if(k == -1 || s[j] == s[k])
{
j++; k++;
nx[j] = k;
}
else k = nx[k];
}
}
int main()
{
int count=1;
while( scanf("%d", &n) && n!=0)
{
int j=0;
scanf("%s", s);
get_next();
printf("Test case #%d\n", count++);
for(int i=2; i<=n; i++)
{
if(nx[i] <= 0)
continue;
j = i - nx[i];
if(i % j == 0)
printf("%d %d\n", i, i/j);
}
printf("\n");
}
return 0;
}