您的位置:首页 > 其它

poj3461KMP算法模板

2012-04-23 10:55 246 查看
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
char a[1000010],b[1001000];
int next[1001000];
int n,m;
void GetNext(char ch[],int next[])
{
int i=1,j=0;
next[1]=0;
next[0]=0;
while(i<=n)
{
if(j==0||ch[i]==ch[j])
{
++i;++j;next[i]=j;
}
else
j=next[j];
}
}
int KMPIndex(char b[],char a[],int next[])
{
int i=1,j=1,count=0;
if(m<n)
return 0;
while(i<=m)
{
if(j==0||a[j]==b[i])
{
++i;++j;
}
else
j=next[j];
if(j==n+1)  {count++;j=next[j];}
}
return count;

}
int main()
{
int pos,t;
int i,j;
scanf("%d",&t);a[0]='#';b[0]='#';
while(t--)
{
scanf("%s",a+1);
n=strlen(a)-1;
scanf("%s",b+1);
m=strlen(b)-1;
memset(next,0,sizeof(next));
GetNext(a,next);
pos=KMPIndex(b,a,next);
printf("%d\n",pos);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 include