B. Power Strings
Time Limit: 3000ms
Memory Limit: 65536KB
64-bit integer IO format: %lld Java class name: MainGiven 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.
解题:求字符串的循环节长度。利用KMP的适配数组。如果字符长度可以被(字符长度-fail[字符长度])整除,循环节这是这个商,否则循环节长度为1,即就是这个字符本身。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #define LL long long 10 #define INF 0x3f3f3f 11 using namespace std; 12 const int maxn = 1000100; 13 char str[maxn]; 14 int fail[maxn]; 15 void getFail(int &len) { 16 int i,j; 17 len = strlen(str); 18 fail[0] = fail[1]; 19 for(i = 1; i < len; i++) { 20 j = fail[i]; 21 while(j && str[j] != str[i]) j = fail[j]; 22 fail[i+1] = str[j] == str[i] ? j+1:0; 23 } 24 } 25 int main() { 26 int len; 27 while(gets(str) && str[0] != '.') { 28 getFail(len); 29 if(len%(len-fail[len])) puts("1"); 30 else printf("%d ",len/(len-fail[len])); 31 } 32 return 0; 33 }