http://hihocoder.com/problemset/problem/1015
Because the KMP algorithm only pre-preprocess the B-string, so it is suitable for solving, given a string and a bunch of different a strings, ask B is those substring of a string.
or the lookup pattern string appears several times in the original string.
1#include <iostream>2#include <cstdio>3#include <cmath>4#include <vector>5#include <cstring>6#include <string>7#include <algorithm>8#include <string>9#include <Set>Ten#include <functional> One#include <numeric> A#include <sstream> -#include <stack> -#include <map> the#include <queue> - #pragmaComment (linker, "/stack:102400000,102400000") - #defineCL (arr, Val) memset (arr, Val, sizeof (arr)) - + #definell Long Long - #defineINF 0x7f7f7f7f + #defineLC L,m,rt<<1 A #defineRC M + 1,r,rt<<1|1 at #definePi ACOs (-1.0) - - #defineL (x) (x) << 1 - #defineR (x) (x) << 1 | 1 - #defineMID (L, R) (L + R) >> 1 - #defineMin (x, y) (x) < (y)? (x): (y) in #defineMax (x, y) (x) < (y)? (y): (x) - #defineE (x) (1 << (x)) to #defineIabs (x) (x) < 0? -(x): (x) + #defineOut (x) printf ("%i64d\n", X) - #defineLowbit (x) (x) & (-X) the #defineRead () freopen ("A.txt", "R", stdin) * #defineWrite () freopen ("B.txt", "w", stdout); $ #defineMAXN 1000000000Panax Notoginseng #defineN 2510 - #defineMoD 1000000000 the using namespacestd; + A intp[10010]; the Chart1|10010],s2[1000010]; + intn,m; - voidNextintm) $ { $ intj=0; -p[1]=0; - for(intI=2; i<=m;i++) the { - while(j>0&& (s1[j+1]!=s1[i]) j=P[j];Wuyi if(s1[j+1]==s1[i]) j+=1; thep[i]=J; - //printf ("%d\n", P[i]); Wu } - } About $ intKmpintN) - { - intj=0, k=0; - for(intI=1; i<=n;i++) A { + while(j>0&&s1[j+1]!=s2[i]) j=P[j]; the if(s1[j+1]==s2[i]) j=j+1; - if(j==m) $ { thek++; thej=P[j]; the } the //printf ("%d\n", j); - } in returnK; the } the intMain () About { the //freopen ("A.txt", "R", stdin); the intK; thescanf"%d",&k); + for(intI=0; i<k;i++) - { thescanf"%s", s1+1);Bayiscanf"%s", s2+1); theM=strlen (s1+1); the //printf ("%d\n", m); - next (m); -N=strlen (s2+1); theprintf"%d\n", KMP (n)); the } the return 0; the}
Hihocoder 1015 KMP algorithm