The topic string KMP algorithm

Write about their understanding of KMP, we have two strings A and B, A, B beg appeared many times.

This problem can be solved using KMP.

Worst case matching simple O (n ^ 2) a. KMP is a highly efficient algorithm efficiency is O (n) a.

We thought KMP algorithm is the first string and B matches his own, out of a pre-kmp (next) array mismatch rebound in time, thus greatly enhance efficiency.

kmp [1] is defined as -1 on. Being the first so use it.

 1 #pragma GCC optimize(2)
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 const int maxn=1e5+5;
 5 char a[maxn],b[maxn];
 6 int kmp[maxn];
 7 int main()
 8 {
 9     scanf("%s%s",a+1,b+1);
10     int alen=strlen(a+1);
11     int blen=strlen(b+1);
12     for(int i=2,j=0;i<=blen;++i)
13     {
14         while(j&&b[i]!=b[j+1])j=kmp[j];
15         if(b[i]==b[j+1])j++;
16         kmp[i]=j;
17     }
18     int ans=0;
19     for(int i=1,j=0;i<=alen;++i)
20     {
21         while(j&&a[i]!=b[j+1])j=kmp[j];
22         if(a[i]==b[j+1])j++;
23         if(j==blen)ans++;
24     }
25     kmp[1]=-1;
26     for(int i=1;i<=blen;++i)printf("%d ",kmp[i]);
27     printf("\n%d\n",ans);
28     return 0;
29 }
View Code

 

Give a few examples

Luo Gu P3375

hdu1686

hdu1711

hdu2087

Guess you like

Origin www.cnblogs.com/yoududezongzi/p/11305274.html