zoukankan      html  css  js  c++  java
  • 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
    ",kmp_search(src, slen, ptrn, plen, nextval, 0));
    
    
    
    
        }
    
        return 0;
    
    }
    View Code
  • 相关阅读:
    仿新浪微博的ListView下拉更新功能
    Android如何防止apk程序被反编译
    Android横竖屏切换
    如何让Android字体自适应屏幕分辨率
    开工啦,从新浪搬到这儿来。。
    nginx + php +上传大文件
    mac + apache2 +memcached +yii
    ubuntu12.04 + git server+gitosis中央服务器的安装与配置
    virtual box ubuntu 下共享文件夹+全屏显示+修改uuid+cpu虚拟化技术
    ubunut+nginx + yii + url重写(url rewrite)+mac+apache
  • 原文地址:https://www.cnblogs.com/dengyaolong/p/3691497.html
Copyright © 2011-2022 走看看