Application array of nature Period HDU 1358 KMP next

Application array of nature Period HDU 1358 KMP next

Original title link

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 KMPin the algorithm nextapplied 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 nextthe difference array corresponding to the superscript and subscript values, if the difference divisible subscript i, i.e. i%j==0, the description subscript icharacter 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/jcan.

Note: This algorithm can not find next is the kind of simplified form.

It should be special treatment next[i] = 0or next = -1to 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;
}

Guess you like

Origin www.cnblogs.com/alking1001/p/12243767.html