poj3461Oulipo KMP算法

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define X 1000005
char s[X],p[X];
int Next[X],len1,len2;
void shift() //计算移动的模板
{
int i,j = -1;
Next[0] = -1;
for(i=1;i<len2;i++)
{
while(j!=-1&&s[j+1]!=s[i])
j = Next[j];
if(s[j+1]==s[i])
j++;
Next[i] = j;
}
}
int kmp()//kmp的match函数
{
int j = -1, k = 0;
shift();
for(int i=0;i<len2;i++)
{
while(j!=-1&&s[j+1]!=p[i])
j = Next[j];
if(s[j+1]==p[i])
j++;
if(j==len1-1)
{
k++;
j = Next[j];
}
}
return k;
}
int main()
{
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
int t;
cin>>t;
while(t--)
{
scanf("%s%s",s,p);
len1 = strlen(s);
len2 = strlen(p);
cout<<kmp()<<endl;
}
return 0;
}

 

你可能感兴趣的:(poj)