题目链接:https://vjudge.net/problem/POJ-2406
Power Strings
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 52631 | Accepted: 21921 |
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:
求字符串的最小循环节。
1) 如果字符串长度能被“初步的最小循环节”整除,那么这个就是他的最小循环节。
2) 如果字符串长度不能被“初步的最小循环节”整除,那么这个只是它通过补全后的最小循环节。而它实际的最小循环节为自己。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
typedef long long LL;
const double eps = 1e-;
const int INF = 2e9;
const LL LNF = 9e18;
const int MOD = 1e9+;
const int MAXN = 2e6+; char x[MAXN];
int Next[MAXN]; void get_next(char x[], int m)
{
int i, j;
j = Next[] = -;
i = ;
while(i<m)
{
while(j!=- && x[i]!=x[j]) j = Next[j];
Next[++i] = ++j;
}
} int main()
{
while(scanf("%s", x) && strcmp(x, "."))
{
int len = strlen(x);
get_next(x, len);
int r = len-Next[len]; //求出最小循环节
if(len%r) //如果长度/最小循环节除不尽,则对于此字符串来说,实际的最小循环节是自己
printf("1\n");
else
printf("%d\n", len/r);
}
}
后缀数组: