Given a string (1-200000), calculate the sum of the times of successful matching of all its prefixes in itself (Modulo 10007)
Solution: using the features of the next array, when the primary string pointer is mismatched at the pos position, the substring pointer should be adjusted to next [pos] for comparison with the pos, this means that the string 0-(next [pos]-1) should be the same as the (pos-next [pos])-(pos-1) string, the string 0-(next [pos]-1) is exactly the prefix of the string, and the solution is natural. in obtaining the next value of the string 0-N, enumeration I belongs to [1, n], record pos = I, if pos> 0, accumulate answer, pos = next [pos], otherwise accumulate the value of I.
Code:
[Cpp]
# Include <iostream>
Using namespace std;
Const int MAXN = 222222, MOD = 10007;
Char s [MAXN];
Int T, N, next [MAXN];
Void makenext (){
Int I = 0, j =-1;
Next [0] =-1;
While (I <= N ){
If (s [I] = s [j] | j =-1) next [++ I] = ++ j;
Else j = next [j];
}
}
Int solve (){
Int sum = 0, pos;
For (int I = 1; I <= N; I ++ ){
Pos = I;
While (pos ){
Sum = (sum + 1) % MOD;
Pos = next [pos];
}
}
Return sum; www.2cto.com
}
Int main (){
Scanf ("% d", & T );
While (T --){
Scanf ("% d", & N );
Scanf ("% s", s );
Makenext ();
Printf ("% d \ n", solve ());
}
Return 0;
}
Author: Airarts _