HDU 1618 Oulipo KMP Problem
Returns two strings to find the frequency at which one string appears in another string.
In the past, there was another trap in kmp. The following notes show that if the subscript is not well performed, there will be a certain probability of timeout and errors, depending on the specific string.
Just modify it. The kmp speed is very fast.
# Include
# Include
Const int MAX_TXT = 1000001; const int MAX_WORD = 10001; int gWlen, gTlen; char word [MAX_WORD]; int next [MAX_WORD]; char txt [MAX_TXT]; void getNext () {memset (next, 0, sizeof (int) * gWlen); for (int I = 1, j = 0; I <gWlen ;) {if (word [I] = word [j]) next [I ++] = ++ j; else if (j> 0) j = next [J-1]; else I ++ }}int kmpSearch () {int I = 0, j = 0, ans = 0; for (; gWlen-j <= gTlen-I ;) {if (word [j] = txt [I] ) {J ++; I ++; if (j = gWlen) {ans ++; j = next [J-1];} // else I ++; I ++ times out here, which is a probability of timeout. Note that! } Else if (j> 0) j = next [J-1]; else I ++;} return ans;} int main () {int T; scanf ("% d ", & T); getchar (); while (T --) {gets (word); gWlen = strlen (word); gets (txt); gTlen = strlen (txt ); getNext (); printf ("% d \ n", kmpSearch ();} return 0 ;}