Hihocoder.com on the KMP algorithm problem, engaged in a half-day in VS2012 is able to pass, submit up is a problem, repeatedly change finally passed, record here, the following is the test through the code. Input
The first line, an integer n, represents the number of test data groups.
The next n^2 line, each of the two lines represents a test data. In each test data, the first behavior pattern string consists of no more than 10^4 uppercase letters, the second behavior of the original string, consisting of no more than 10^6 uppercase letters.
where n<=20
Output
For each test data, output a line of ans in the order in which they appear in the input, indicating the number of times the pattern string appears in the original string.
Sample input
5HAHAHAHAWQNWQNADAADADADABABABBBABABABABABABABABBDADADDAADAADDAAADAAD
Sample output
31310
1#include <iostream>2 //vs2012 with #include<string> can, g++ do not want to use. h, because strlen () is defined in g++ header file, not used string.h, toss half a day3#include <string.h>using namespacestd;4 voidKmpnext (Char* Pattern,intMint*p) {5p[0] =0;6 intK =0;7 for(inti =1; I < m; i++){8 while(k >0&& Pattern[k]! =Pattern[i]) {9K = p[k-1];Ten } One if(Pattern[k] = =Pattern[i]) { AP[i] = + +K; -}Else{ -P[i] =0;//k = = 0 the } - } - } - intKmpChar* STR,intStartChar* Pattern,intKintMint*p) { + //int k = 0; - inti =start; + while(Str[i]! =' /'){ A while(k >0&& str[i]! = pattern[k]) k = p[k-1]; at if(Str[i] = =Pattern[k]) { -k++; - if(k = = m)returnI-m +1; - } -i++; - } in return-1; - } to intMatchChar* STR,Char* Pattern,intMint*p) { + intRET =0; - inti =0; the intK =0; * while(Str[i]! =' /'){ $ intIDX =KMP (str, I, pattern, K, M, p);Panax Notoginseng if(idx = =-1) Break; -ret++; theK = p[m-1]; +i = idx +m; A } the returnret; + } - intMain () { $ intN; $CIN >>N; - Charpattern[10001]; - Charstr[1000001]; the intp[10001]; - //char *pattern = new char[10001];Wuyi //char *str = new char[1000001]; the //int *p = new int[10001]; - for(inti =0; i < N; i++){ Wu //getline (CIN, Pattern[i]); - //getline (CIN, Str[i]); AboutCIN >>pattern; $CIN >>str; - intm =strlen (pattern); - Kmpnext (Pattern, M, p); - intnum =match (str, pattern, M, p); Acout<<num<<Endl; + } the //delete []pattern; - //delete []str; $ //delete []p; the}
Hihocoder #1015: KMP algorithm