oulipo——KMP

传送门

‎法国作家乔治·佩雷克(Georges Perec,1936-1982)曾经写过一本书,没有字母‎‎“e”。‎‎他是Oulipo小组的成员。书中的一句话:‎

‎一切都有正常的对等,但一切都声称是假的。一切都正常,首先,非人出现了,吓坏了他。他很想知道将他与小说联系在一起的关联在哪里:搅动他的地毯,随时攻击他的想象力,禁忌的直觉,晦涩邪恶的景象,空洞的东西,不言而喻的:异象,遗忘的异象支配一切,理性被废除:一切看起来正常,但......‎

‎佩雷克可能会在随后的比赛中得分很高(或者更确切地说,得分很低)。人们被要求在某个主题上写一篇甚至可能有意义的文本,尽可能少地出现一个给定的“单词”。我们的任务是为陪审团提供一个计算这些事件的程序,以获得竞争对手的排名。这些竞争对手经常写很长的文字,毫无意义;连续500,000个‎‎序列的“T”‎‎并不罕见。他们从不使用空间。‎

‎因此,我们希望快速找出单词(即给定字符串)在文本中出现的频率。更正式地说:给定字母表{‎‎'A'‎‎,‎‎'B'‎‎,‎‎'C'‎‎,...,‎‎'Z'‎‎}和该字母表上的两个有限字符串,一个单词‎‎W‎‎和一个文本‎‎T‎‎,计算‎‎W‎‎在‎‎T‎‎中的出现次数。W 的所有连续字符必须与 ‎‎T‎‎ 的连续字符完全匹配。具体值可能会重叠。‎

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

InputcopyOutputcopy
3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN
1
3
0

#include<iostream>
#include<vector>
#include <cstring>
#include<algorithm>
using namespace std;
void get_next(char ch[],int l,int next[])//数组从0开始计数
{
	next[0]=-1;
	int i=0,j=-1;
	while(i<=l)
	{
		if(j==-1||ch[i]==ch[j])
		next[++i]=++j;
		else
		j=next[j];
		
	}
}

int num(int ll,int l,int next[],char a[],char b[])
{
	
	int j=0,ans=0;
	for(int i=0;i<ll;i++)
	{
		while(b[i]!=a[j]&&j>0)
		{
			j=next[j];
		}
		if(b[i]==a[j])
		{
			j++;
		}
		if(j==l)
		{
			ans++;
			j=next[j];
		}
	}
	return ans;
}

int main()
{
	int n;
	cin>>n;
	char a[10005];
	char b[1000005];
	int l,ll,next[10005];
	while(n--)
	{
		cin>>a>>b;
		l=strlen(a);
		ll=strlen(b);
		get_next(a,l,next);
		cout<<num(ll,l,next,a,b)<<endl;
		
	}
 } 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linalw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值