POJ 2406 KMP

来源:互联网 发布:武汉美工速成班 编辑:程序博客网 时间:2024/06/02 22:39

题目大意:
给一个串,由n个连续的重复子串构成,输出n。以句号停止输入。
理解:
用KMP的next数组求解,next数组记录的是前面的串前缀和后缀相同的最大长度。n与next【len】有关。这里写图片描述

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int MAXN=1e6+5;int next[MAXN];char s[MAXN];void get_next(char* s){    int len=strlen(s);    int i=0,j=-1;    next[0]=-1;    while(i<len){        if(j==-1||s[i]==s[j]){            i++;            j++;            next[i]=j;        }        else {            j=next[j];        }    }}int main(){  while(~scanf("%s",s)){    if(strcmp(s,".")==0)break;    get_next(s);    int len=strlen(s);    if(len%(len-next[len])==0){        printf("%d\n",len/(len-next[len]));    }    else {        printf("1\n");    }  } return 0;}
0 0
原创粉丝点击