hdu1711 KMP

来源:互联网 发布:linux 加载u盘 编辑:程序博客网 时间:2024/05/20 18:17
    #include <bits/stdc++.h>    using namespace std;    const int maxn=1e6+10; int  str[maxn],mo[maxn],N,M;    int Next[maxn];    void getnext()    {        int i=0,j=-1;        while(i<M)        {            if(j==-1||mo[i]==mo[j]){Next[++i]=++j;}            else j = Next[j];        }    }    int KMP()    {        int i=0,j=0;        int ans=0;        while(i<N)        {            if(j==-1||mo[j]==str[i])i++,j++;            else j=Next[j];            if(j==M)return i-M+1;        }        return -1;    }    int main()    {        int t,i; scanf("%d",&t);        while(t--)        {        scanf("%d %d",&N,&M);         for(i=0;i<N;i++)scanf("%d",&str[i]);         for(i=0;i<M;i++)scanf("%d",&mo[i]);         if(M>N)printf("-1\n");         else{            Next[0]=-1;            getnext();         printf("%d\n",KMP());         }        }        return 0;    }

原创粉丝点击