[kuangbin专题] KMP

三世轮回 提交于 2019-11-27 10:03:42

https://vjudge.net/contest/278481

 

A - Oulipo

可重叠匹配,KMP裸题

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<cstring>
 4 using namespace std;
 5 const int MAXW=1e4+5;
 6 const int MAXT=1e6+5;
 7 char strW[MAXW],strT[MAXT];
 8 int lenW,lenT;
 9 int Next[MAXW];
10 void GetNext()
11 {
12     int k=Next[0]=-1;
13     int j=0;
14     while(j<lenW)
15     {
16         if(k==-1||strW[k]==strW[j]) Next[++j]=++k;
17         else k=Next[k];
18     }
19 }
20 int kmp()
21 {
22     int i=0,j=0,ans=0;
23     while(i<lenT)
24     {
25         if(j==-1||strT[i]==strW[j]) ++i,++j;
26         else j=Next[j];
27         if(j==lenW)
28         {
29             ans++;
30             j=Next[j];
31         }
32     }
33     return ans;
34 }
35 int read()
36 {
37     int s=1,x=0;char ch=getchar();
38     while(!isdigit(ch)) {if(ch=='-') s=-1;ch=getchar();}
39     while(isdigit(ch)) {x=10*x+ch-'0';ch=getchar();}
40     return s*x;
41 }
42 int main()
43 {
44     int cas=read();
45     while(cas--)
46     {
47         scanf("%s",strW);
48         scanf("%s",strT);
49         lenW=strlen(strW);
50         lenT=strlen(strT);
51         GetNext();
52         /*for(int i=1;i<=lenW;++i)
53         cout<<Next[i]<<' ';*/
54         cout<<kmp()<<endl;
55     }
56 }
View Code

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!