POJ 2406 Power Strings

 

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]));
    }
}

 

posted @ 2015-10-29 21:19  Pat  阅读(180)  评论(0编辑  收藏  举报