Language:DefaultPeriod
| Time limit:3000 Ms |
|
Memory limit:30000 K |
| Total submissions:13504 |
|
Accepted:6365 |
Description For each prefix of a given string s with n characters (each character has an ascii code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. that is, for each I (2 <= I <= N) We want to know the largest K> 1 (if there is one) such that the prefix of S with length I can be written as AK, that is a concatenated K times, for some string. of course, we also want to know the period K.Input The input consists of several test cases. each test case consists of two lines. the first one contains N (2 <= n <= 1 000 000)-the size of the string S. the second line contains the string S. the input file ends with a line, having Number zero on it.Output For each test case, output "Test Case #" And the consecutive test case number on a single line; then, for each prefix with length I that has a period K> 1, output the prefix size I and the period K separated by a single space; the prefix sizes must be in increasing order. print a blank line after each test case.Sample Input 3aaa12aabaabaabaab0 Sample output Test case #12 23 3Test case #22 26 29 312 4 Source Southeastern Europe 2004 |
The length is the prefix of I (2 <= I <= N). If the prefix is a periodic string, the length of I and its maximum cycle are output; find all the matching items.
Idea: The next [I] array contains the maximum length of the same prefix and suffix of the string before the I position. If it is a periodic string, then it must meet I % (I-next [I]) = 0.
Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <algorithm> # include <cmath> # include <string> # include <map> # include <stack> # include <vector> # include <set> # include <queue> # pragma comment (linker, "/Stack: 102400000,102400000") # define maxn 1005 # define maxn 1000010 # define mod 1000000009 # define INF 0x3f3f3f # define PI ACOs (-1.0) # define EPS 1e-6typedef long ll; using namespace STD; int n EXT [maxn]; char STR [maxn]; int N; void get_next () {int I = 0, j =-1; next [0] =-1; while (I <n) {If (j =-1 | STR [I] = STR [J]) {I ++; j ++; next [I] = J;} else J = next [J] ;}} void KMP () {for (INT I = 1; I <= N; I ++) // enumerate all lengths to see if it is full or does not meet the requirements {If (! (I % (I-next [I]) & (I/(I-next [I])> 1) // output printf ("% d \ n", I, I/(I-next [I]) when the condition is met;} int main () {int CAS = 1; while (scanf ("% d", & N) {scanf ("% s", STR); get_next (); printf ("Test Case # % d \ n", CAS ++); KMP (); printf ("\ n");} return 0 ;}/ * 3aaa12aabaabaabaab0 */
Period (poj 1961 & HDU 1358) KMP