Question link:
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1686
Question meaning:
For two strings, calculate the number of repetitions of the first string in the second string, which can overlap.
Solution:
Directly use KMP. If a match is successful, set J to next [J.
Code:
# Include <iostream> # include <cmath> # include <cstdio> # include <cstdlib> # include <string> # include <cstring> # include <algorithm> # include <vector> # include <map> # include <stack> # include <list> # include <queue> # define EPS 1e-6 # define Inf (1 <30) # define PI ACOs (-1.0) using namespace STD; # define maxn1 11000 # define maxn2 1100000 # define ll _ int64char save1 [maxn1], save2 [maxn2]; int next [maxn1], N1, N2; void getnext () {Int J = 0; next [1] = 0; For (INT I = 2; I <= N1; I ++) {While (j> 0 & save1 [J + 1]-save1 [I]) J = next [J]; if (save1 [J + 1] = save1 [I]) J ++; next [I] = J;} return; // note that the next array stores the maximum length of A1 ---- an-1} ll KMP () {Int J = 0; ll ans = 0; For (INT I = 1; I <= n2; I ++) {While (j> 0 & save1 [J + 1]-save2 [I]) J = next [J]; if (save1 [J + 1] = save2 [I]) J ++; If (j = N1) {ans ++; j = next [J]; // It can be repeated. If it cannot be repeated, set J to 0} return ans;} int main () {int t; scanf ("% d", & T ); while (t --) {scanf ("% S % s", save1 + 1, save2 + 1); save1 [0] = save2 [0] = 'K '; n1 = strlen (save1)-1, n2 = strlen (save2)-1; // printf ("% d \ n", N1, N2); getnext (); printf ("% i64d \ n", KMP ();} return 0 ;}