Oulipo HDU - 1686(KMP算法理解)

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

题意:
给出一个模式串和主串,查找主串中有几个模式串。

解析:
KMP算法模板题;

什么是KMP算法:
KMP算法是一种改进的字符串匹配算法,KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next()函数实现,函数本身包含了模式串的局部匹配信息。
简单点讲就是:在已匹配的前缀当中寻找到最长可匹配后缀子串和最长可匹配前缀子串,在下一轮直接把两者对齐,从而实现模式串的快速移动。

首先是把主串和模式串的首位对齐,从左到右对逐个字符进行比较。
在这里插入图片描述
模式串和主串的第一个等长子串比较,发现前5个字符都是匹配的,第6个字符失配;
在这里插入图片描述
我们可以发现,在前缀“GTGTG”当中,后三个字符“GTG”和前三位字符“GTG”是相同的:
在这里插入图片描述
在下一轮的比较时,只有把这两个相同的片段对齐,才有可能出现匹配。这两个字符串片段,分别叫做最长可匹配后缀子串和最长可匹配前缀子串。
在这里插入图片描述
这样就可以减少无谓的字符串比较

而要实现模板串的快速移动,就需要知道每一次失配后字符串移动的位置,这个时候就需要引入一个next数组来记录这些位置。KMP算法最难理解的也就是这个next数组了
next数组的下标代表了“已匹配前缀的下一个位置”,元素的值则是“最长可匹配前缀子串的下一个位置”。
这里我们利用模板,来实现next数组的建立;

void getnx()
{
	int i=0,j=-1;
	nx[0]=-1;
	while(i<l1)
	{
		if(j==-1||s1[i]==s1[j])
		{
			++i;
			++j;
			nx[i]=j;//把相同的最大前缀和最大后缀长赋给next[i]
		}
		else
		j=nx[j];//如果下一个不同,那么j就变成next[j];
	}
}

用一组数据模拟一下过程,就基本理解这个代码了;
之后再调用模板,对其进行主串进行遍历,过程见上面那几张图。

void kmp()
{
	int cnt=0,i=0,j=0;
    while(i<l2)
	{
		if(j==-1||s1[j]==s2[i])
		{
			++i;
			++j;
		}
		else j=nx[j];//失配后回到最大前缀后面
		if(j==l1)
		{
			j=nx[j];//这里要注意,如果等于0,则模式串从0开始,就不能算有重合部分的情况了
			cnt++;
		}
	}
	printf("%d\n",cnt);
}

完整代码:

#include"stdio.h"
#include"string.h"
#include"algorithm"
using namespace std;
char s1[10010],s2[1000010];
int nx[10010],l1,l2;
void getnx()
{
	int i=0,j=-1;
	nx[0]=-1;
	while(i<l1)
	{
		if(j==-1||s1[i]==s1[j])
		{
			++i;
			++j;
			nx[i]=j;//把相同的最大前缀和最大后缀长赋给next[i]
		}
		else
		j=nx[j];//如果下一个不同,那么j就变成next[j];
	}
}
void kmp()
{
	int cnt=0,i=0,j=0;
    while(i<l2)
	{
		if(j==-1||s1[j]==s2[i])
		{
			++i;
			++j;
		}
		else j=nx[j];//失配后回到最大前缀后面
		if(j==l1)
		{
			j=nx[j];//这里要注意,如果等于0,则模式串从0开始,就不能算有重合部分的情况了
			cnt++;
		}
	}
	printf("%d\n",cnt);
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%s %s",s1,s2);
		l1=strlen(s1);
		l2=strlen(s2);
		if(l1>l2)
		{
			printf("0\n");
			continue;
		}
		getnx();
		kmp();
	}
	return 0;
}

知识点补充:l-nx[l],表示最小循环节长度

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值