Description
The French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter ‘e’. He was a member of the Oulipo group. A quote from the book:
Tout avait Pair normal, mais tout s’affirmait faux. Tout avait Fair normal, d’abord, puis surgissait l’inhumain, l’affolant. Il aurait voulu savoir où s’articulait l’association qui l’unissait au roman : stir son tapis, assaillant à tout instant son imagination, l’intuition d’un tabou, la vision d’un mal obscur, d’un quoi vacant, d’un non-dit : la vision, l’avision d’un oubli commandant tout, où s’abolissait la raison : tout avait l’air normal mais…
Perec would probably have scored high (or rather, low) in the following contest. People are asked to write a perhaps even meaningful text on some subject with as few occurrences of a given “word” as possible. Our task is to provide the jury with a program that counts these occurrences, in order to obtain a ranking of the competitors. These competitors often write very long texts with nonsense meaning; a sequence of 500,000 consecutive ‘T’ s is not unusual. And they never use spaces.So we want to quickly find out how often a word, i.e., a given string, occurs in a text. More formally: given the alphabet {‘A’, ‘B’, ‘C’, …, ‘Z’} and two finite strings over that alphabet, a word W and a text T, count the number of occurrences of W in T. All the consecutive characters of W must exactly match consecutive characters of T. Occurrences may overlap.
Input
The first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:
- One line with the word W, a string over {
'A','B','C', …,'Z'}, with 1 ≤ |W| ≤ 10,000 (here |W| denotes the length of the string W). - One line with the text T, a string over {
'A','B','C', …,'Z'}, with |W| ≤ |T| ≤ 1,000,000.
Output
For every test case in the input file, the output should contain a single number, on a single line: the number of occurrences of the word W in the text T.
Sample Input
1 | 3 |
Sample Output
1 | 1 |
Analysis
KMP板题….
给出两个字符串,其中一个是另一个的子串,求子串P在母串T中出现了多少次。
显然暴力做法是从左到右一个个匹配,如果有某个字符不匹配,就跳回去,把字串右移。当然这是肯定会超时的。
观察发现,当匹配失败时,我们已经知道前面有一些字符是匹配的了,这时仅仅右移一位就显得很笨拙。而KMP的思想是:利用已经部分匹配这个有效信息,保持i指针不回溯,通过修改j指针,让模式串尽量地移动到有效的位置。
所以整个KMP的重点在于:当某一个字符与主串不匹配时,我们应该知道j指针要移动到哪?
如下图,C和B不匹配了,可以把j移到第2位,因为前面有两个字母是一样的:


可看出,当匹配失败时,j要移动的下一个位置k有这样的性质:最前面的k个字符和j之前的最后k个字符是一样的。

如上图,有公式:
那么
因为P的每一个位置都可能发生不匹配,所以用一个next数组保存每一个位置j对应的k,next[j]=k,表示当$T[i]!=P[j]$时,j的下一个位置。函数getnext()即为其过程。


对比这两个图发现规律:
证明:
当$P[k]!=P[j]$时,如下图

此时应为$k=next[k]$,如下图

然而上述算法还有点缺陷


如图,这一步移动毫无意义,因为后面的B已经不匹配,那么前面的B肯定也不匹配,原因在于$P[j]==P[next[j]]$。所以在getnext()中特判一下这种情况就ok了。
Code
1 |
|