Power Strings
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 24582 | Accepted: 10329 |
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
分析:本题大意就是一个字符串s最多可有几个s1连续组合而成 s = s1s1s1s1...;哈哈到这儿也就明白了这题考察什么了吧。对你没有看错是最小循环节。kmp算法的next求法是否还记得。next的一个很重要的应用就是求最小循环节。公式是这样的
假如len能整除len-next[len]则最小循环节就是len-next[len].知道最小循环节也就很easy求出最大个数了len/(len-next[len])
#include <iostream>
#include <cstring>
using namespace std;
int k = 0;
int next[1000005];
char a[1000005];
void getnext(char* a, int len)
{
int i = 0, j = -1;
next[0] = -1;
while (i < len )
{
while (j >= 0 && a[i] != a[j] )
{
j = next[j];
k++;
}
i++;
j++;
next[i] = j;
}
if (len%(len-j)==0)
{
cout<<len/(len-j)<<endl;
}
else
cout<<"1"<<endl;
}
int main()
{
while (cin >> a&& strcmp(a, ".")!=0)
{
getnext(a, strlen(a));
}
return 0;
}