pku 2527 Seek the Name, Seek the Fame(KMP next数组应用)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXN 400005

char name[MAXN];
int next[MAXN];
bool first;

void getNext(int len)
{
    int j=0,k=-1;
    next[0]=-1;
    while(j<len)
    {
        if( k == -1 || name[j] == name[k] )
        {
            ++j;
            ++k;
            next[j] = k;
        }
        else k=next[k];
    }
}

void print(int i)
{
    if( next[i] > 0)
        print( next[i] );
    if(first)
    {
        printf("%d",i);
        first=false;
    }
    else printf(" %d",i);
}

int main()
{
    while(scanf("%s",name)!=EOF)
    {
        int len=strlen(name);
        getNext(len);
        //   for(int i=0;i<=len;i++) printf("%2d ",next[i]);
        //   printf("\n");
        //    printf("%d",len);
        first=true;
        print(len);
        printf("\n");
    }
}

posted @ 2010-08-27 14:22  菜到不得鸟  阅读(116)  评论(0)    收藏  举报