码迷,mamicode.com
首页 > 其他好文 > 详细

POJ-2406 Power Strings(KMP)

时间:2017-01-17 16:12:13      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:int   cpp   blog   har   present   normal   exce   each   ret   

题目描述:

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\n");
    else{
        int x=n-1-nxt[n-1];
        if(n%x) printf("1\n");
        else{
            if(check(x)) printf("%d\n",n/x);
            else printf("1\n");
        }
    }
}

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

 


POJ-2406 Power Strings(KMP)

标签:int   cpp   blog   har   present   normal   exce   each   ret   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!