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.
题目大意:求字符串的循环节数
KMP求串的前后缀相同长度,然后求循环节数
#include <cstdio> #include <cstring> #include <iostream> using namespace std; int len; int p[1000010]; char s[1000010]; int main() { for (;;) { scanf("%s", s + 1); if (s[1] == '.') break; len = strlen(s + 1); int j = 0; p[1] = 0; for (int i = 2; i <= len; ++i) { while (j && s[j + 1] != s [i]) j = p[j]; if (s[j + 1] == s[i]) ++j; p[i] = j; } if (len % (len - p[len]) == 0) printf("%d\n", len / (len - p[len])); else printf("1\n"); } }