KMP模板

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cstring>
 5 
 6 using namespace std;
 7 const int N=1e6+5;
 8 char s[N],t[10005];
 9 
10 void strstr(){
11     int next[10005];
12     memset(next,0,sizeof(next));
13     next[0]=-1;
14     int j=0,k=-1;
15     while(j<strlen(t)){
16         if(k==-1||(t[j]==t[k])){
17             next[++j]=++k;
18         }
19         else k=next[k];
20     }
21     j=0,k=0;
22     int num=0;
23     while(j<strlen(s)){
24         if(k==-1||(s[j]==t[k])){
25             j++,k++;
26         }
27         else k=next[k];
28         if(k==strlen(t)) num++,k=next[k];
29     }
30     printf("%d\n",num);
31 }
32 
33 int main()
34 {
35     int n;
36     cin>>n;
37     while(n--){
38         cin>>t>>s;
39         strstr();
40     }
41 }
View Code

 

posted @ 2019-06-07 20:32  厂长在线养猪  Views(91)  Comments(0Edit  收藏  举报