P3375 [TEMPLATE] KMP string matching (fully annotated, easy to understand), p3375kmp

Description

For example, two strings s1 and s2 are given, where s2 is the Child string of s1, and all the positions where s2 appears in S1.

In order to reduce the number of spoofing points, the prefix array next of the substring is also output. If you do not know what this means, do not ask, go to Baidu search [kmp algorithm] to learn it.

Input/Output Format

**Input Format:**
The first row is a string, that is, s1 (only uppercase letters are contained)

The second behavior is a string, that is, s2 (containing only uppercase letters)

**Output Format:**
Several rows. Each row contains an integer indicating the position where s2 appears in s1.

The next line, including the length (s2) integers, indicates the value of the prefix array next [I.

Input and Output sample

**Input example #1:**
ABABABCABA

**Output sample #1:**
130 0 1

Description

Time-Space limit: 1000 ms, 128 M

Data scale:

Set s1 length to N, s2 length to M

For 30% of data: N <= 15, M <= 5

For 70% of data: N <= 10000, M <= 100

For 100% of data: N <= 1000000, M <= 1000

Example:

So the two matching locations are 1 and 3, and the output is 1 and 3.

Bare KMP

Thinking Source http://www.cnblogs.com/c-cloud/p/3224788.html

1 # include <iostream> 2 # include <cstdio> 3 # include <cstring> 4 using namespace std; 5 const int MAXN = 1000001; 6 char a [MAXN], B [MAXN]; 7 int la, lb; 8 int p [MAXN]; 9 void makep () 10 {11 int j = 0; // record the longest length of the common prefix and suffix; 12 p [0] = 0; // The first number of prefixes and suffixes are empty sets, so it is 0 13 for (int I = 1; I <lb; I ++) // the first one is 0, so starting from 1, the semi-closed semi-open interval 14 {15 while (j> 0 & B [j]! = B [I]) // when there is a mismatch, let j get an element that can continue to match from the p array 16 j = p [J-1]; // because the last processing of j is j ++, and p starts from 0, so j = p [J-1] 17 if (B [j] = B [I]) // if they are the same, let j ++ give an example and try 18 j ++; 19 p [I] = j; // record the length of each element's longest common prefix and suffix for later processing 20} 21} 22 void KMP () 23 {24 int j = 0; // The longest matched length is 25 for (int I = 0; I <la; I ++) 26 {27 if (j> 0 & B [j]! = A [I]) // when the element to be matched does not want to be the same and finds the same Matching Element 28 j = p [J-1]; // when j = 0, p [-1] does not exist, so j> 0 29 if (B [j] = a [I]) // Similarly, when the elements to be matched are the same, j ++ 30 j ++; 31 if (j = lb) // find a matching 32 printf ("% d \ n ", I + 1-lb + 1); 33 // because I, lb is counted from 0, so + 1 34} 35} 36 int main () 37 {38 scanf ("% s", a, B); 39 la = strlen (a); lb = strlen (B ); // count the length of the two strings by 40 makep (); // construct the p array by 41 KMP (); // 42 for (int I = 0; I <lb; I ++) printf ("% d", p [I]); 43 return 0; 44}