Power Strings(字符串的n次方)

poj2406

题目大意:给出一个字符串,求出是某个字符串的n次方

解决:KMP找出字符串的循环节

若有字符串ai...a(j+m),若next[len+1]=m(字符串从1开始),意味着从ai ...am 和 aj...a(j+m)相等,假设中间有相交部分(或者相交部分为0)aj....am,若总长度减去相交部分剩余的部分能被总长度整除,又因为  从ai ...am 和 aj...aj+m相等,所以除去相交部分剩余的的两段字符串相等,而且必定满足中间相交部分也能被起始字符串整除,依照这样,即可得出最小的循环节  

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char str[1000005];
short next[1000005];
int main()
{
    while(scanf("%s",str+1),str[1]!='.')
    {
        int len=strlen(str+1);
        int i=1,j=0,cnt=0;
        next[1]=0;
        while(i<=len)
        {
            if(j==0 || str[i]==str[j])
            {
                i++;j++;
                next[i]=j;
            }
            else j=next[j];
        }
        if(len%(len-next[len+1]+1)==0)
           printf("%d\n",len/(len-next[len+1]+1));
        else printf("1\n");
    }
    system("pause");
    return 0;
}

原文地址:https://www.cnblogs.com/hpustudent/p/2163800.html