uvalive 3026 Period (前綴最短循環節)

給一個長度爲n的字符串S,求其每一個前綴的最短循環節(若存在)


對於串S,利用KMP算法求一下Next數組

根據next數組的含義,設當前前綴長度爲i,若這i個字符組成周期串,則i-next[i]恰好爲其週期串的最長長度。

#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
typedef long long LL;
using namespace std;
#define maxn 1000005
int Next[maxn];
void GetNext(char *T)
{
    int i=0,j=-1;
    Next[0]=-1;
    while(T[i]!='\0')
    {
        if(j==-1||T[i]==T[j]) Next[++i]=++j;
        else j=Next[j];
    }
}
char S[maxn];
int main()
{
    int ca=1,n;
    while(~scanf("%d",&n)&&n)
    {
        scanf("%s",S);
        GetNext(S);
        printf("Test case #%d\n",ca++);
        for(int i=2;i<=n;++i)
            if(i/(i-Next[i])>1&&(i%(i-Next[i])==0))
                printf("%d %d\n",i,i/(i-Next[i]));
        puts("");
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章