poj3461KMP匹配

来源:互联网 发布:rhel7关闭linux防火墙 编辑:程序博客网 时间:2024/06/06 10:51

经典KMP

重要点在于NEXT数组的使用


#include<cstdio>#include<cstring>#define MAXN 1010010#define MAXM 11000using namespace std;char N1[MAXN],M1[MAXM];int T,N,M,next[MAXM];void createnext(int M){    int i=0,j=-1;    next[i]=-1;    while(i<M){        if(j==-1||M1[i]==M1[j]){            i++;j++;            next[i]=j;        }        else{            j=next[j];        }    }}int kmp(int N,int M){    int i = 0, j = 0,ans = 0;    while(i<N)    {        if(N1[i]==M1[j]||j==-1)i++,j++;        else j = next[j];        if(j==M)        {            ans++;            j = next[j-1];            i--;        }    }    return ans;}int main(){    scanf("%d",&T);    while(T--)    {        memset(N1,0,sizeof(N1));        memset(M1,0,sizeof(M1));        memset(next,0,sizeof(next));        scanf("%s%s",M1,N1);        N = strlen(N1),M = strlen(M1);        createnext(M);        printf("%d\n",kmp(N,M));    }    return 0;}

原创粉丝点击