[KMP求最小周期]POJ 2406 Power Strings

来源:互联网 发布:交男朋友的软件 编辑:程序博客网 时间:2024/04/29 20:03

传送门:http://poj.org/problem?id=2406

题意:给定一个字符串,让你求出他最多由几个相同的连续子串连接而成。

思路:求出这个字符串的最小周期,然后用总长度/最小周期长度即是解。

关于如何求最小周期:这里YY了一个方法,就是把该字符串增长一倍,然后拿原来的字符串做模式,增长后的字符串做主串,用KMP求模式在主串第1个位置(下标为0,包含第一个位置)之后的第一个匹配位置,就是最小周期长度。(如何证明当然不会啦。。。。。仅仅是YY出来的,没想到AC了。)

代码:

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int MAXN = 11111111;char T[MAXN<<1],P[MAXN];int Next[MAXN];void MakeNext(int M){    int i=0,j=-1;    Next[0] = -1;    while(i<M){        if(j==-1||P[i]==P[j]){            i++,j++;            if(P[i]!=P[j])Next[i]=j;            else Next[i] = Next[j];        }        else j = Next[j];    }}int KMP(int pos,int N,int M){    int i = pos,j = 0;    while(i<N&&j<M){        if(j==-1||T[i]==P[j])i++,j++;        else j = Next[j];    }    if(j==M) return i-M;    else return -1;}int main(){    while(scanf("%s",P),P[0]!='.'){        int N,M;        M = strlen(P);        N = M<<1;        strcpy(T,P);        strcpy(T+M,P);        MakeNext(M);        int pos = KMP(1,N,M);        int m = pos;        printf("%d\n",M/m);    }    return 0;}


 

原创粉丝点击