Power Strings
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 52620 | Accepted: 21917 |
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算法的经典应用.利用next数组来求,next[i]表示的是匹配到第i位后要跳回到第next[i]位去继续匹配,这里的匹配可以相当于是自己和自己匹配.(next[i],i]表示的字符串就可能是一个循环节.如果i - next[i] | len,那么i - next[i]就是答案,否则循环节就是字符串本身.因为每次跳到next[i]的时候,(next[i],i]的字符串已经和前面的匹配好了,而(2*next[i] - i,next[i]]也与前面匹配好了,所以(next[i],i]就有可能是一个循环节.如果不整除的话,就会有余数位不能被匹配,也就不能构成循环节了.
一开始的想法是求min{i - next[i]},事实上是错的,因为只保证了i前面的能匹配上,后面的不能保证.为了保证这个循环节是整个字符串的循环节,i取len.
strlen函数非常慢,要少用QAQ
#include <cstdio> #include <cmath> #include <queue> #include <cstring> #include <iostream> #include <algorithm> using namespace std; char s[1000010]; int nextt[1000010]; int main() { while (scanf("%s", s + 1) != 0) { if (s[1] == '.') break; nextt[0] = 0; int j = 0, len = strlen(s + 1); for (int i = 2; i <= len; i++) { while (j && s[j + 1] != s[i]) j = nextt[j]; if (s[j + 1] == s[i]) j++; nextt[i] = j; } int t = len - nextt[len]; if (len % t == 0) printf("%d ", len / t); else printf("%d ", 1); } return 0; }