↓ 跳过正文
  1. Posts/

KMP算法学习

·943 字·2 分钟

20170801update:当时竟然没有强调 next 函数的含义?

next[i] 的含义是,i 之前的整个前缀中,最长的「前缀和后缀相同」的长度。

看图:

KMP 前后缀匹配示意

KMP 感觉是我学到现在最难懂的一个算法了 QAQ 为什么你们都那么强啊,看几个小时就看懂了……

先放一波我觉得值得看的资料: kmp算法讲解(配图比较全……) kmp学习资料2

说下我对 KMP 算法的理解:

理解 KMP 算法大概分成两个部分。

一部分是理解一个 naive 的 KMP 算法,可以叫 “fast slide” algorithm

思想大概就是,当 mismatch 发生时,我们并不是一无所有,而是知道 mismatch 发生前已匹配字符的信息。

失配后模式串滑动示意

然后知道这些信息我们可以做什么呢?

先观察一下最最暴力的求解字符串匹配的算法:

 1//***********************************************************
 2//brute force
 3 n = T.length();
 4      m = P.length();
 5
 6      i0 = 0;              // Line P up with the first character of T
 7      i = 0;               // Start matching with first char in T
 8      j = 0;               // Start matching with first char in P
 9
10      while ( i < n )     // Not all characters used
11      {
12         if ( T[i] == P[j] )
13         {
14            /* ===============================================
15	       T[i] and P[j] match ==> try next pair
16	       =============================================== */
17            i++;           // Match next pair
18            j++;
19
20            if ( j == m )
21               return ( i0 );    // Match found at position i0 !!!
22         }
23         else
24         {  /* ===========================================
25               T[i] ≠ P[j]:
26                  1. Slide P up 1 position
27		  2. restart from beginning of string
28               =========================================== */
29            i0 = i0 + 1;   // Slide pattern P one character further
30
31            i  = i0;       // Restart matching at position i0 in T
32            j  = 0;        // Restart matching at position 0 in P
33         }
34      }
35
36      return -1;           // Return not found
37   }

这个算法低效在,当 mismatch 发生时,我只是往前移动了一个字符。

因此我们定义了 maxoverlap 函数。

**需要特别强调的是,**这样我们就可以利用 maxoverlap 函数来优化 mismatch 发生时移动的过程。

 1  KMP( T,  P )
 2   {
 3      int i0, i, j, m, n;
 4
 5      n = T.length();
 6      m = P.length();
 7
 8      i0 = 0;              // Line P up with the first character of T
 9      i = 0;               // Start matching with first char in T
10      j = 0;               // Start matching with first char in P
11
12      while ( i < n )     // Not all characters used
13      {
14         if ( T[i] == P[j] )
15         {
16            i++;           // Match next pair
17            j++;
18
19            if ( j == m )
20               return ( i0 );    // Match found atposition i0 !!!
21         }
22         else
23         {  /* ===========================================
24	       T[i] ≠ P[j]
25               =========================================== */
26
27             if ( j == 0 )
28	     {  /* ==============================================
29	           First character already mismatched
30		   We have NO prefix info. to work with...
31		   =============================================== */
32	        i0++;        // Just slide P 1 character over
33		i = i0;      //
34		j = 0;
35             }
36	     else
37             {
38	        prefix = P[ 0..(j-1) ];  // Prefix of pattern at the mismatch
39
40	        k = MaxOverlap( prefix );
41
42	        j = k;
43	        i0 = (i - j);
44		// i is unchanged !
45             }
46         }
47      }
48
49      return -1;           // No match found
50   }

这样我们就得到了 “fast slide” algorithm 算法。

但是,能不能再给力一点呢?

我们发现,上述代码中,我们每次都要计算一次 maxoverlap 函数。

但是,一个字符串的子串个数是有限的。

我们能不能加速这个过程呢?

很容易想到预处理一波。

也就是求所谓的 failure function,中文应该叫失配函数……

所以第二部分就是如何快速求出失配函数

这也是我认为的 KMP 算法最精(nan)髓(dong)的地方。

相关文章

poj 2406 Power Strings (后缀数组||kmp)

·1756 字·4 分钟
poj 2406 题意:给定一个字符串 L,已知这个字符串是由某个字符串 S 重复 R 次而得到的, 求 R 的最大值 思路:论文题。 转载论文中的题解: 做法比较简单,穷举字符串 S 的长度 k,然后判断是否满足。判断的时候, 先看字符串 L 的长度能否被 k 整除,再看 suffix(1) 和 suffix(k+1) 的最长公共前缀是否等于 n-k。在询问最长公共前缀的时候,suffix(1) 是固定的,所以 RMQ 问题没有必要做所有的预处理,只需求出 height 数组中的每一个数到 height[rank[1]] 之间的最小值即可。整个做法的时间复杂度为 O(n)

whust 2016 #1 D Zhenya moves from the dormitory (贪心,模拟)

·491 字·1 分钟
题目链接 傻逼模拟。。读完题就ac了。。。 代码实现 1/* *********************************************** 2Author :111qqz 3Created Time :2016年08月07日 星期日 18时04分18秒 4File Name :code/whust2016/#1/D.cpp 5************************************************ */ 6#include <cstdio> 7#include <cstring> 8#include <iostream> 9#include <algorithm> 10#include <vector> 11#include <queue> 12#include <stack> 13#include <set> 14#include <map> 15#include <string> 16#include <cmath> 17#include <cstdlib> 18#include <deque> 19#include <ctime> 20#define fst first 21#define sec second 22#define lson l,m,rt<<1 23#define rson m+1,r,rt<<1|1 24#define ms(a,x) memset(a,x,sizeof(a)) 25typedef long long LL; 26#define pi pair < int ,int > 27#define MP make_pair 28using namespace std; 29const double eps = 1E-8; 30const int dx4[4]={1,0,0,-1}; 31const int dy4[4]={0,-1,1,0}; 32const int inf = 0x3f3f3f3f; 33const int N=280; 34int n,m; 35int total,adva,advb; 36struct Friend 37{ 38 int money; 39 int adv; 40}f[N]; 41struct Room 42{ 43 int type; 44 int cost; 45 int adv; 46}r[N]; 47struct Ans 48{ 49 int val; 50 int rid; 51 int fid; 52 bool operator < (Ans b)const 53 { 54 return val>b.val; 55 } 56}ans[300*300]; 57int main() 58{ 59 #ifndef ONLINE_JUDGE 60 freopen("code/in.txt","r",stdin); 61 #endif 62 cin>>total>>adva>>advb; 63 cin>>n; 64 for ( int i = 1 ; i <= n ; i++) 65 scanf("%d %d",&f[i].money,&f[i].adv); 66 scanf("%d",&m); 67 for ( int i = 1 ; i <= m ; i++) 68 scanf("%d%d%d",&r[i].type,&r[i].cost,&r[i].adv); 69 int cnt = 0 ; 70 for ( int i = 1 ; i <= m ; i++) 71 { 72 if (r[i].type==1) 73 { 74 if (r[i].cost<=total) 75 { 76 cnt++; 77 ans[cnt].val = r[i].adv+adva; 78 ans[cnt].rid = i; 79 ans[cnt].fid = -1; 80 } 81 continue; 82 } 83 else 84 { 85 for ( int j = 0 ; j <= n ; j++) 86 { 87 if (j==0) //自己住双人间 88 { 89 if (r[i].cost<=total) 90 { 91 cnt++; 92 ans[cnt].val = r[i].adv+advb; 93 ans[cnt].rid = i ; 94 ans[cnt].fid = -1; 95 } 96 } 97 else 98 { 99 if (r[i].cost<=total*2&&r[i].cost<=f[j].money*2) 100 { 101 cnt++; 102 ans[cnt].val = r[i].adv+f[j].adv; 103 ans[cnt].rid = i ; 104 ans[cnt].fid = j; 105 } 106 } 107 } 108 } 109 } 110// for ( int i = 1 ; i <= cnt ; i++) 111// { 112// printf("val:%d room: %d friend : %d \n",ans[i].val,ans[i].rid,ans[i].fid); 113// } 114 if (cnt==0) 115 { 116 puts("Forget about apartments. Live in the dormitory."); 117 }else 118 { 119 sort(ans+1,ans+cnt+1); 120 if (r[ans[1].rid].type==1) 121 { 122 printf("You should rent the apartment #%d alone.\n",ans[1].rid); 123 } 124 else 125 { 126 if (ans[1].fid==-1) 127 { 128 printf("You should rent the apartment #%d alone.\n",ans[1].rid); 129 } 130 else 131 { 132 133 printf("You should rent the apartment #%d with the friend #%d.\n",ans[1].rid,ans[1].fid); 134 135 } 136 } 137 } 138 #ifndef ONLINE_JUDGE 139 fclose(stdin); 140 #endif 141 return 0; 142}

whust 2016 #1 H - Pair: normal and paranormal

·426 字·1 分钟
题目链接 其实就是括号匹配的模型。。用栈即可。。被我写挂好几发。。该死该死。。。 代码实现 1/* *********************************************** 2Author :111qqz 3Created Time :2016年08月07日 星期日 17时34分13秒 4File Name :code/whust2016/#1/HH.cpp 5************************************************ */ 6 7#include <cstdio> 8#include <cstring> 9#include <iostream> 10 11#include <algorithm> 12#include <vector> 13#include <queue> 14#include <stack> 15#include <set> 16#include <map> 17#include <string> 18#include <cmath> 19#include <cstdlib> 20#include <deque> 21#include <ctime> 22#include <cctype> 23#define fst first 24#define sec second 25#define lson l,m,rt<<1 26#define rson m+1,r,rt<<1|1 27#define ms(a,x) memset(a,x,sizeof(a)) 28typedef long long LL; 29#define pi pair < int ,int > 30#define MP make_pair 31 32using namespace std; 33const double eps = 1E-8; 34const int dx4[4]={1,0,0,-1}; 35const int dy4[4]={0,-1,1,0}; 36const int inf = 0x3f3f3f3f; 37const int N=1E4+7; 38char st[N]; 39int s[N]; 40int n; 41int plow[N]; 42int pup[N]; 43int ans[N]; 44stack<int>stk; 45 46 47bool ok(int x, int y) 48{ 49 // cout<<"x:"<<x<<" y:"<<y<<endl; 50 if (plow[x]>0&&pup[y]>0) 51 { 52 ans[pup[y]] = plow[x]; 53 return true; 54 } 55 if (plow[y]>0&&pup[x]>0) 56 { 57 ans[pup[x]] = plow[y]; 58 return true; 59 } 60 return false; 61} 62int main() 63{ 64 #ifndef ONLINE_JUDGE 65 freopen("code/in.txt","r",stdin); 66 #endif 67 68 cin>>n>>st; 69 n*=2; 70 int cntA = 0 ; 71 int cnta = 0 ; 72 ms(pup,0); 73 ms(plow,0); 74 for ( int i = 0 ; i < n ; i++) 75 { 76 if (st[i]>='a'&&st[i]<='z') 77 { 78 cnta++; 79 plow[i] = cnta; 80 } 81 else 82 { 83 cntA++; 84 pup[i] = cntA; 85 } 86 } 87// for ( int i = 0 ; i < n ; i++) cout<<"plow[i]:"<<plow[i]<<" pup[i]:"<<pup[i]<<endl; 88 for ( int i = 0 ; i < n ; i++) 89 { 90 st[i] = toupper(st[i]); 91 } 92// cout<<"st:"<<st<<endl; 93 ms(ans,-1); 94 while (!stk.empty()) stk.pop(); 95 stk.push(0); 96 for ( int i = 1 ; i < n ; i++) 97 { 98 while (!stk.empty()&&st[stk.top()]==st[i]&&ok(stk.top(),i)&&i<n) 99 { 100 stk.pop(); 101 i++; 102 } 103 stk.push(i); 104 } 105 for ( int i = 1 ; i <= n/2 ; i++) 106 { 107 if (ans[i]==-1) 108 { 109 puts("Impossible"); 110 return 0; 111 } 112 } 113 for ( int i = 1 ; i < n/2 ; i++) printf("%d ",ans[i]); 114 printf("%d\n",ans[n/2]); 115 116 #ifndef ONLINE_JUDGE 117 fclose(stdin); 118 #endif 119 return 0; 120}

hdu 3415 Max Sum of Max-K-sub-sequence (单调队列)

·784 字·2 分钟
hdu 3415 题意:给出n个整数,是一个环(也就是a[n]右边是a[1])求一段长度不超过k的数使得和最大,问最大和是多少并给出这段数的位置。 思路:为了处理环,先把n个数复制一下就好,然后求前缀和sum[i]

ural 1126. Magnetic Storms (单调队列模板题)

·900 字·2 分钟
ural 1126 题意:n个数,求从第k个元素开始,求每k个元素的最大值(一共求n-k+1次) 思路:单调队列。 单调队列学习链接 其实单调队列挺容易的理解的。。。当时觉得写不明白大概是因为看到的代码写得太丑了2333