Power Strings
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 45251 | Accepted: 18884 |
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.
题目:字符串a*b等于a+b,比如“abc”’*“bcd”=“abcbcd”
现有一个字符串问你最多由多少相同子串相乘构成,也就要求子串越小越好。
如:abcd ans:1
aaaa 4
ababab 3
定理:假设S的长度为l,则S存在循环子串,当且仅当,l 可以被l - next [ l ]整除,最短循环子串为S[l - next[ l ]]
证明:
设S=q1q2q3q4q5q6q7q8,并设next[8] = 6,此时str = S[l - next[l]] = q1q2,由字符串特征向量next的定义可知,q1q2q3q4q5q6 = q3q4q5q6q7q8,即有q1q2=q3q4,q3q4=q5q6,q5q6=q7q8,即q1q2为循环子串,且易知为最短循环子串。由以上过程可知,若len可以被len - next[len]整除,则S存在循环子串,否则不存在。
所以:利用KMP算法,求字符串的特征向量next,若l可以被l - next[l]整除,则最大循环次数n为l/(l- next[l]),否则为1。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int next[1000010];
void Next(char a[],int l)
{
next[0]=0;
for(int i=1;i<l;i++)
{
int k=next[i-1];
while(k>0&&a[k]!=a[i])
k=next[k-1];
if(a[k]==a[i])
next[i]=k+1;
else next[i]=0;
}
}
int main()
{
char a[1000010];
while(~scanf("%s",a))
{
if(a[0]=='.')
break;
int l=strlen(a);
Next(a,l);
if(l%(l-next[l-1])==0)
printf("%d\n",l/(l-next[l-1]));
else
printf("1\n");
}
return 0;
}