KMP初學(1)LA 3026 週期

分析:

KMP算法入門題,只用到NEXT[]數組,主要在於NEXT[]數組的構建,詳細介紹見我前幾篇博客,KMP初學

if (next[i] >0 && i%(i-next[i]) == 0)
                printf("%d %d\n",i,i/(i-next[i]));


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn=1000005;

int next[maxn];

void getNext(int m,string str)
{
    int j=-1;
    next[0]=j;
    int i=0;
    while (i<m)
    {
        while (j != -1 && str[i] != str[j])
            j=next[j];
        i++;j++;
        if (j>=m) next[i]=next[j-1];
        else next[i]=j;
    }
}
//-1 0 1 0 1 2 3 4 5 6 7 8 9
int main()
{
    /*string str="aabaabaabaab";
    int len=str.size();*/
    int len;
    string str;
    int kase=0;
    while (~scanf("%d",&len) && len)
    {
        cin>>str;
        memset(next,0,sizeof(next));
        printf("Test case #%d\n", ++kase);
        getNext(len,str);
        for (int i=2;i<=len;i++)
        {
            if (next[i] >0 && i%(i-next[i]) == 0)
                printf("%d %d\n",i,i/(i-next[i]));//精髓所在
        }
    }

    /*for (int i=0;i<=len;i++)
        printf("%d ",next[i]);*/
    return 0;

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