POJ-2406 Power Strings(KMP)

题目描述:

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd
aaaa
ababab
.
Sample Output
1
4
3

题目大意:给一个字符串,求最短的循环节的长度.
题目分析:使用kmp算法求出next数组,length-1-next[length-1]即为最短循环节的长度.

AC代码如下:
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;

const int N=1000000;

int nxt[N+5];
char s[N+5];

void getNext(char *s)
{
    int n=strlen(s);
    nxt[0]=nxt[1]=0;
    for(int i=1;i<n;++i){
        int j=nxt[i];
        while(j&&s[i]!=s[j]) j=nxt[j];
        nxt[i+1]=(s[i]==s[j])?j+1:0;
    }
}

bool check(int x)
{
    int n=strlen(s);
    for(int i=0;i+x<n;i+=x){
        int j=i+x,k=i;
        while(k<i+x){
            if(s[k]!=s[j]) return false;
            ++j,++k;
        }
    }
    return true;
}

void solve()
{
    int n=strlen(s);
    if(n==1) printf("1
");
    else{
        int x=n-1-nxt[n-1];
        if(n%x) printf("1
");
        else{
            if(check(x)) printf("%d
",n/x);
            else printf("1
");
        }
    }
}

int main()
{
    //freopen("in.txt","r",stdin);
    while(~scanf("%s",s)&&!strchr(s,'.'))
    {
        getNext(s);
        solve();
    }
    return 0;
}

原文地址:https://www.cnblogs.com/20143605--pcx/p/6293462.html