Power Strings
Time Limit: 3000MS |
Memory Limit: 65536K |
|
Total Submissions: 39291 |
Accepted: 16315 |
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
【思路】
KMP。
应用KMP算法中的失配函数,如果是一个周期串那么错位部分(n-f[n])一定是一个最小循环节(仔细想想f函数的意义),则答案为i/(n-f[n])。否则ans=1。
时间复杂度为O(n)。
【代码】
#include<cstdio>
#include<cstring>
#include<iostream>
#define FOR(a,b,c) for(int a=(b);a<=(c);a++)
using namespace std; const int maxn = +; void getFail(char* P,int* f) {
int m=strlen(P);
f[]=f[]=;
for(int i=;i<m;i++) {
int j=f[i];
while(j && P[i]!=P[j]) j=f[j];
f[i+]=P[i]==P[j]?j+:;
}
} char s[maxn];
int f[maxn]; int main() {
while(scanf("%s",s)== && s[]!='.') {
getFail(s,f);
int n=strlen(s);
if(f[n]> && n%(n-f[n])==) printf("%d\n",n/(n-f[n]));
else printf("%d\n",);
}
return ;
}