https://vjudge.net/contest/278481
可重叠匹配,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 }