KMP的模版实现(以hdu1711为例)

贴代码,觉得带template的有一些大材小用……不过还是按自己风格写吧!

/*******************************************************************************/
/* OS           : 3.2.0-58-generic #88-Ubuntu SMP Tue Dec 3 UTC 2013 GNU/Linux
 * Compiler     : g++ (GCC)  4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
 * Encoding     : UTF8
 * Date         : 2014-04-26
 * All Rights Reserved by yaolong.
*****************************************************************************/
/* Description: ***************************************************************
*****************************************************************************/
/* Analysis: ******************************************************************
*****************************************************************************/
/*****************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>

using namespace std;
template<typename S,typename T>
void get_nextval(S const * ptrn,T plen,T *nextval){

    T i=0;  //i从0开始
    nextval[i]=-1;
    T j=-1;
    while(i<plen){

        if(j==-1||ptrn[i]==ptrn[j]){  
            ++i;
            ++j;
            //if(ptrn[i]!=ptrn[j]){
                 nextval[i]=j;
          //  }else nextval[i]=nextval[j];


        }else j=nextval[j];         
    }
}
template<typename S,typename T>
T kmp_search(S const * src,T slen,S const *ptrn,T plen,T const *nextval,T pos){


     T i=pos,j=0;
    while(i<slen)
    {
        if(src[i]==ptrn[j])
        {
            if(j==plen-1)  return i-(plen-1)+1;
            i++;j++;
        }
        else
        {
            j=nextval[j];
            if(j==-1)   {i++;j=0;}
        }
    }
    return -1;

}
int src[1000501],ptrn[15001];
int nextval[15001];
int main(){



    int T,slen,plen,i;
    scanf("%d",&T);
    while(T--){
  
    scanf("%d%d",&slen,&plen);
    for(i=0;i<slen;i++){
        scanf("%d",src+i);


    }
    for(i=0;i<plen;i++){

        scanf("%d",ptrn+i);
    }

    get_nextval(ptrn, plen, nextval);

    printf("%d\n",kmp_search(src, slen, ptrn, plen, nextval, 0));




    }

    return 0;

}
View Code

 

posted @ 2014-04-26 14:19  dengyaolong  阅读(193)  评论(0编辑  收藏  举报