KMP算法心得

学了这个算法,思路倒是不难懂,但是看了代码后却很绕,特别晕,一直有一个地方不太懂,现在才颇有感受。

next[0]为什么要赋值-1,以及这样的话char数组与next不就不对应了吗?

比如a[3]对应的next数组便是next[4],但是跳跃的时候却是用next[3]

直到后来我准备自己实施代码时发现上面的做法太棒了

举个例子

数组1              :      a b c a b y x

对应的next数组:-1 0 0 0 1 2 0 0 

数组2               :abcabcabyx

如图,当对应到第5个元素时(对应数组的下标),数组1为y,数组2为c,不匹配,于是第一个数组的下标j = next[j],即j = next[5] = 2,所以第一个数组下标就跳到第2个元素,也就是c了,c再与数组2的c匹配,完美!

如果不加上next[0] = -1会变成怎么样?那么每次匹配不成功,必须j = next[j-1],而且无法判断是否已经回到了首元素。


附上刚刷的一道例题:

Oulipo
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 46057   Accepted: 18369

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

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN

Sample Output

1
3
0


题意:

找出第一个字符串在第二个字符串中出现次数。

 
 

附上AC代码:

#include <cstdio>  
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define ll long long
char a[11111];
int next[11111];
char b[1111111];
int lena;
int lenb;
int sum = 0;
void getnext()
{
	int i,j;
	next[0] = j = -1;
	i = 0;
	while(i < lena)
	{
		while(j != -1 && a[i] != a[j])
			j = next[j];
		next[++i] = ++j;
	}
}
void kmp()
{
	int i,j;
	j = 0;
	i = 0;
	while(i < lenb)
	{
		while(j != -1 && a[j] != b[i])
			j = next[j];
		i++;j++;
		if(j >= lena)
		{
			sum++;
			j = next[j];
		}
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		sum = 0;
		scanf("%s%s",a,b);
		lena = strlen(a);
		lenb = strlen(b);
		getnext();
		kmp();
		/*for(int i = 0;i <= len;i++)
			cout << next[i] << ' ';
		cout << endl;*/
		printf("%d\n", sum);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mmmmmmmw/article/details/79804746