poj2406 Power Strings

Power Strings
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 28668   Accepted: 11976

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.
kmp next数组的应用,next[n]表示str[0-next[i]]与str[n-next[n],n]相等,以str[0,next[i]]为循环节!
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#define MAXN 1005000
char str[MAXN];
int next[MAXN],n;
int getnext(){
    next[0]=next[1]=0;
    int i,j;
    for(i=1;i<n;i++){
        j=next[i];
        while(j&&str[i]!=str[j]){
            j=next[j];
        }
        next[i+1]=str[i]==str[j]?j+1:0;
    }
}
int main (){
    int i;
    while(scanf("%s",str)!=EOF){
        n=strlen(str);
        if(n==1&&str[0]=='.')break;
        getnext();
        int ans=0x4f4f4f4f;
        if(n%(n-next[n])==0){
            printf("%d\n",n/(n-next[n]));
        }
        else
            printf("1\n");
    }
    return 0;
}


你可能感兴趣的:(poj2406 Power Strings)