【POJ2406】【KMP】Power Strings
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
【分析】
其实我是来贴诗句的。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 唐代李白 3 《三五七言 / 秋风词》 4 5 秋风清,秋月明, 6 落叶聚还散,寒鸦栖复惊。 7 相思相见知何日?此时此夜难为情! 8 入我相思门,知我相思苦。 9 长相思兮长相忆,短相思兮无穷极。 10 早知如此绊人心,何如当初莫相识。 11 */ 12 #include <iostream> 13 #include <cstdio> 14 #include <algorithm> 15 #include <cstring> 16 #include <vector> 17 #include <utility> 18 #include <iomanip> 19 #include <string> 20 #include <cmath> 21 #include <queue> 22 #include <assert.h> 23 #include <map> 24 #include <ctime> 25 #include <cstdlib> 26 #include <stack> 27 #define LOCAL 28 const int MAXN = 1000000 + 10; 29 const int INF = 100000000; 30 const int SIZE = 450; 31 const int MAXM = 1000000 + 10; 32 const int maxnode = 0x7fffffff + 10; 33 using namespace std; 34 int l1, l2; 35 char a[MAXN], b[MAXN]; 36 int next[1000000];//不用开太大了.. 37 void getNext(){ 38 //初始化next数组 39 next[1] = 0; 40 int j = 0; 41 for (int i = 2; i <= l1; i++){ 42 while (j > 0 && a[j + 1] != a[i]) j = next[j]; 43 if (a[j + 1] == a[i]) j++; 44 next[i] = j; 45 } 46 return; 47 } 48 int kmp(){ 49 int j = 0, cnt = 0; 50 for (int i = 1; i <= l2; i++){ 51 while (j > 0 && a[j + 1] != b[i]) j = next[j]; 52 if (a[j + 1] == b[i]) j++; 53 if (j == l1){ 54 cnt++; 55 j = next[j];//回到上一个匹配点 56 } 57 } 58 return cnt; 59 } 60 61 void init(){ 62 scanf("%s", a + 1); 63 scanf("%s", b + 1); 64 l1 = strlen(a + 1); 65 l2 = strlen(b + 1); 66 } 67 68 int main(){ 69 int T; 70 71 while (scanf("%s", a + 1)){ 72 if (a[1] == '.') break; 73 l1 = strlen(a + 1); 74 getNext(); 75 if (l1%(l1 - next[l1]) == 0) printf("%d\n", l1/(l1 - next[l1])); 76 else printf("1\n"); 77 } 78 return 0; 79 }