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

POJ 2406 Power Strings

时间:2015-10-29 23:05:41      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

 

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 38908   Accepted: 16170

Description

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

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

Source

-------------------------------------------------
做之前已经知道tag是KMP了,但一时想不出如何KMP,乱写一发竟然AC了。
把我乱搞的代码和正解都贴这里,留给自己回味吧。。。。。
 
#include <cstdio>
using namespace std;

const int N(1e6+5);
char s[N];
int nt[N];

int main(){
    for(int k, ls, p, ans; scanf("%s", s), *s!=.; printf("%d\n",ans)){
        k=0;
        for(int i=ls=1; s[i]; i++, ls++){
            for(;k&&s[k]!=s[i];k=nt[k-1]);
            nt[i]=s[k]==s[i]?++k:k;
        }
        p=ls-nt[ls-1];
        ans=1;
        if(p&&ls%p==0){
            ans=ls/p;
            for(int i=ls; i; i-=p)
                if(i-nt[i-1]!=p){
                    ans=1;
                    break;
                }
        }
    }
}

正解在此

#include <cstdio>
using namespace std;

const int N(1e6+5);
char s[N];
int nt[N];

int main(){
    for(int k, ls, p, ans; scanf("%s", s), *s!=.;){
        k=0;
        for(int i=ls=1; s[i]; i++, ls++){
            for(;k&&s[k]!=s[i];k=nt[k-1]);
            nt[i]=s[k]==s[i]?++k:k;
        }
        printf("%d\n", ls%(ls-nt[ls-1])?1:ls/(ls-nt[ls-1]));
    }
}

 

POJ 2406 Power Strings

标签:

原文地址:http://www.cnblogs.com/Patt/p/4921848.html

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