[KMP-NEXT array features] HDU 3336 Count the string

Source: Internet
Author: User

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 _

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.