[POJ 2406] Power Strings【KMP】

• 2018-02-20
• 0
• 0

Problem:

 Time Limit: 3000MS Memory Limit: 65536K

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

Waterloo local 2002.07.01

Solution:

• len = c * k (c ∈ N*)s1..(c-1)k == sk+1..ck
• s1..k == sk+1..2k == …… == s(c-1)k+1..ck

Code: O(T|s|) [5564K, 141MS]

```#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;

char s;
int nxt;

int main(){
while(scanf("%s", s + 1) != EOF && s != '.'){
int len = strlen(s + 1);
nxt = 0;
for(register int i = 2, j = 0; i <= len; i++){
while(j && s[j + 1] != s[i]) j = nxt[j];
if(s[j + 1] == s[i]) j++;
nxt[i] = j;
}
if(len % (len - nxt[len])) puts("1");
else printf("%d\n", len / (len - nxt[len]));
}
return 0;
}
```

评论

49750

https://github.com/Darkleafin

OPEN AT 2017.12.10

If the code cannot be displayed normally, please refresh the page.

https://visualgo.net/en

- Theme by Qzhai