Http://poj.org/problem? Id = 2752
The next Array application of KMP. In a word, next [J] must be the maximum value that satisfies STR [1 .. next [J] = STR [J-next [J] + 1. J.
Take abababa as an example. If next [7] = 5, STR [1 .. 5] = STR [3 .. 7], apparently STR [3 .. 5] = STR [5 .. 7].
Next [5] = 3, STR [1 .. 3] = STR [3 .. 5], according to the above results, we can see STR [1 .. 3] = STR [5 .. 7].
Because of the nature of the next array, it is clear that the above is true for any situation, and the value saved by each next can make STR [1 .. next [J] = STR [Len-next [J] + 1 .. len].
Here we only need to find the non-zero value of next from Len to 1, and then output it in reverse order.
Code:
# Include <cstdio>
# Include <cstring>
Char STR [400001];
Int next [400001];
Int ans [400001];
Int Len;
Void get_next () {// based on known next
Next [1] = 0;
Int J = 0;
For (INT I = 2; I <= Len; I ++ ){
While (j> 0 & STR [J + 1]! = STR [I])
J = next [J];
If (STR [J + 1] = STR [I]) J ++;
Next [I] = J;
}
}
Int main (){
Int I, J;
While (~ Scanf ("% s", STR + 1 )){
Len = strlen (STR + 1 );
Get_next ();
Ans [0] = I = Len;
J = 1;
While (next [I]> 0 ){
Ans [J ++] = next [I];
I = next [I];
}
For (I = J-1; I> = 0; I --)
Printf ("% d", ANS [I]);
Printf ("\ n ");
}
Return 0;
}