zoukankan      html  css  js  c++  java
  • 扩展KMP模板

    具体原理可以参考这里:扩展KMP扩展KMP算法(刘毅)

    代码:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 using namespace std;
     6 const int N=1e6+5;
     7 
     8 int len1,len2;
     9 int nxt[N],extend[N];       //nxt[i]表示t[0...len2-1]和t[i...len2-1]的最大公共前缀长度
    10                             //extend[i]表示s[i...len1-1]和t[0...len2-1]的最大公共前缀长度
    11 
    12 //获得next[i](0<=i<=len(t)),跟ex_kmp()类似,相当于字符串自身t匹配,t[i..len2-1]和t[0...len2-1]和等价于s和t
    13 void getnext(char *t){
    14     int a,p,len;
    15     len=strlen(t);
    16     nxt[0]=len;
    17     for(int i=1,j=-1;i<len;i++,j--){
    18         if(j<0||i+nxt[i-a]>=p){
    19             if(j<0)
    20                 p=i,j=0;
    21             while(p<len&&t[p]==t[j])
    22                 p++,j++;
    23             nxt[i]=j;
    24             a=i;
    25         }
    26         else
    27             nxt[i]=nxt[i-a];
    28     }
    29 }
    30 
    31 //求得extend[i](0=<i<=len(s))
    32 void ex_kmp(char *s,char *t){
    33     int a,p,len1,len2;               //记录匹配成功的字符的最远位置p,及起始位置a
    34     len1=strlen(s);
    35     len2=strlen(t);
    36     for(int i=0,j=-1;i<len1;i++,j--){//j即等于p与i的距离,其作用是判断i是否大于p(如果j<0,则i大于p)
    37         if(j<0||i+nxt[i-a]>=p){      //i大于p(其实j最小只可以到-1,j<0的写法方便读者理解程序)
    38             if(j<0)
    39                 p=i,j=0;
    40             while(p<len1&&j<len2&&s[p]==t[j])
    41                 p++,j++;
    42             extend[i]=j;
    43             a=i;
    44         }
    45         else
    46             extend[i]=nxt[i-a];
    47     }
    48 }
  • 相关阅读:
    Codeforces 424C(异或)
    CodeForces
    Codeforces 424A (思维题)
    HDU 1197 Specialized Four-Digit Numbers
    ZOJ 2301 Color the Ball 线段树(区间更新+离散化)
    HDU 1106 排序
    Codefroces 831B Keyboard Layouts
    POJ 1082 Calendar Game
    HDU 多校联合 6045
    HDU 5976 Detachment
  • 原文地址:https://www.cnblogs.com/fu3638/p/8503523.html
Copyright © 2011-2022 走看看