天天看點

HDU 1358 Period(KMP+next數組的運用)

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as A  K , that is A concatenated K times, for some string A. Of course, we also want to know the period K. 

Input

The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S. The second line contains the string S. The input file ends with a line, having the number zero on it. 

Output

For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case. 

Sample Input

3
aaa
12
aabaabaabaab
0      

Sample Output

Test case #1
2 2
3 3

Test case #2
2 2
6 2
9 3
12 4      

題解:

給你一個串,從第二位起到最後的每一個i,問你從串的第一位到第i位是否能形成一個循環節,如果可以,輸出目前的i和可以找到最多循環節的循環的次數

思路:

直接KMP搞一搞就好了,i-next[i]就相當于目前最小的循環節長度,設為t,當t%i==0&&t/i>1的時候即就是能形成循環的時候,因為KMP求出的就是最多的循環次數,輸出t/i就是了

代碼:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<math.h>
#include<string>
#include<stdio.h>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<deque>
using namespace std;
#define lson k*2
#define rson k*2+1
#define M (t[k].l+t[k].r)/2
#define INF 1008611111
#define ll long long
#define eps 1e-15
int Next[1000005];
char T[1000005];
void init()
{
    int i,j;
    i=0,j=-1;
    Next[0]=-1;
    while(T[i])
    {
        if(j==-1||T[i]==T[j])
        {
            i++;
            j++;
            Next[i]=j;
        }
        else
            j=Next[j];

    }
}
int main()
{
    int i,j,n,cas=1;
    while(scanf("%d",&n)!=EOF&&n)
    {
        scanf("%s",T);
        init();
        printf("Test case #%d\n",cas);
        cas++;
        for(i=1;i<=n;i++)
        {
            int t=i-Next[i];
            if(i%t==0&&i/t>1)
            {
                printf("%d %d\n",i,i/t);
            }
        }
        printf("\n");
    }
    return 0;
}
           

繼續閱讀