KMP algorithm learning notes and kmp learning notes
Http://www.matrix67.com/blog/archives/115
Orz maxtix67
I 've been dragging on to the question of the KMP algorithm ..
String A: abefgababef
Mode string B: abefgabef
When A matches B, if I is the pointer on A and j is the pointer on B, A and B will be mismatched if they match to 8th bits. According to the general method, we will jump I back to 2 and j back to 1 for matching. After observation, we will find that this is redundant because the befg in the middle is impossible. We should jump directly to the 6th bits of A for matching.
The KMP algorithm accelerates matching by filtering useless characters ..
As an example, when abefgab has been matched and the next digit is not matched, the next AB can be used directly as the start of a new match, because AB is the prefix and suffix of abefgab. This provides us with an idea. If we can find the largest matched string, that is, the prefix and suffix of the substring (it is called the prefix and suffix) we can put it directly in the next match, which reduces the time complexity. The question now is how to find the largest prefix and suffix of each pattern string ..
Make s [I] The I prefix of the pattern string, that is, the string consisting of the first I bit. p [I] is the maximum length of the prefix and suffix of s [I, suppose we know that p [I] requires p [I + 1]. In fact, this is a pattern string's own matching process. If s [I + 1] = s [p [I] + 1], that is, the maximum prefix and the next suffix match, obviously, p [I + 1] = p [I] + 1; if they are not equal, return and find the largest prefix and suffix of p [I] Next. In this way, continue to retreat, one will always match, otherwise p [I + 1] will be 0. In this way, we get the p array. When matching, we can follow the process of p ..
Get the p array:
void getp(){j=0;p[0]=0;for (i=1;i<m;i++){while (j&&b[j]!=b[i]) j=p[j-1];if (b[j]==b[i]) j++;p[i]=j;}}Codevs1404:
#include<iostream>#include<cstdio>#include<memory.h>#define maxn 200005char a[maxn],b[maxn];int i,j,n,m,k,x,p[maxn],len[maxn],cnt[maxn];void getp(){j=0;p[0]=0;for (i=1;i<m;i++){while (j&&b[j]!=b[i]) j=p[j-1];if (b[j]==b[i]) j++;p[i]=j;}}void match(char *a,char *b){int i,j=0;for (i=0;i<n;i++){while (j&&b[j]!=a[i]) j=p[j-1];if (b[j]==a[i]) j++;cnt[j]++;if (j==m) j=p[j-1];}}int main(){scanf("%d%d%d\n%s\n%s",&n,&m,&k,&a,&b);getp();memset(cnt,0,sizeof(cnt));match(a,b);for (i=m;i>=1;i--) cnt[p[i-1]]+=cnt[i];for (i=1;i<=k;i++){scanf("%d",&x);printf("%d\n",cnt[x]-cnt[x+1]);}}