hdu1358 KMP-next数组的应用

来源:岁月联盟 编辑:猪蛋儿 时间:2012-11-17

hdu1358

next数组贮存的是String中前i位字符 最长相同的前后缀长度+1。
i-next[i] 则表示前i 位中循环节的长度

[cpp] 
#include<iostream> 
#include<cstdio> 
using namespace std; 
 
char T[1000010];  www.2cto.com
int next[1000010]; 
int N,M; 
 
void GetNext() 

    int i=1,j=0;    next[1]=0; 
     
    while(i<=N) 
    { 
        if(j==0 || T[i]==T[j]) 
        { 
            ++i;++j; 
            next[i]=j; 
        } 
        else    j=next[j]; 
    } 

 
int main() 

    int t=1,i,j,num,k; 
    while(scanf("%d",&N)&&N!=0) 
    { 
        scanf("%s",T+1); 
        GetNext(); 
    //  for(i=0;i<=N;i++)    printf("%d ",next[i]);printf("/n"); 
//      for(i=0;i<=N;i++)    printf("%d ",i-next[i]);printf("/n"); 
        printf("Test case #%d/n",t++); 
        for(i=3;i<=N+1;i++) 
        { 
            int Y=(i-1)/(i-next[i]); 
            if((i-1)%(i-next[i])==0&&Y>1)    printf("%d %d/n",i-1,Y); 
        } 
        printf("/n"); 
    } 
    return 0;