POJ2406 Power Strings —— KMP or 后缀数组 最小循环节

题目链接: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) 如果字符串长度不能被“初步的最小循环节”整除,那么这个只是它通过补全后的最小循环节。而它实际的最小循环节为自己。

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <string>
 6 #include <vector>
 7 #include <map>
 8 #include <set>
 9 #include <queue>
10 #include <sstream>
11 #include <algorithm>
12 using namespace std;
13 typedef long long LL;
14 const double eps = 1e-6;
15 const int INF = 2e9;
16 const LL LNF = 9e18;
17 const int MOD = 1e9+7;
18 const int MAXN = 2e6+10;
19 
20 char x[MAXN];
21 int Next[MAXN];
22 
23 void get_next(char x[], int m)
24 {
25     int i, j;
26     j = Next[0] = -1;
27     i = 0;
28     while(i<m)
29     {
30         while(j!=-1 && x[i]!=x[j]) j = Next[j];
31         Next[++i] = ++j;
32     }
33 }
34 
35 int main()
36 {
37     while(scanf("%s", x) && strcmp(x, "."))
38     {
39         int len = strlen(x);
40         get_next(x, len);
41         int r = len-Next[len];  //求出最小循环节
42         if(len%r)       //如果长度/最小循环节除不尽,则对于此字符串来说,实际的最小循环节是自己
43             printf("1
");
44         else
45             printf("%d
", len/r);
46     }
47 }
View Code

后缀数组:

原文地址:https://www.cnblogs.com/DOLFAMINGO/p/7860648.html