Oulipo (哈希)

求模式串在待匹配串的出现次数。

Input

第一行是一个数字T,表明测试数据组数。
之后每组数据都有两行:第一行为模式串,长度不大于10000;第二行为待匹配串,长度不大于1000000。所有字符串只由大写字母组成。

Output

每组数据输出一行结果。

Sample Input

4
ABCD
ABCD
ABA
ABABABA
CDCDCDC
CDC
KMP
NAIVE

Sample Output

1
3
0
0
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;
const int maxm = 1e4 + 5;
const int maxn = 1e6 + 5;
char w[maxm],t[maxn];
ull p = 233;
int main()
{
	int tt;
	scanf("%d",&tt);
	while (tt--)
	{
		int i,j;
		scanf("%s %s",w,t);
		int len1 = strlen(w);
		int len2 = strlen(t);
		if (len1>len2)
		{
			printf("0\n");
			continue;
		}
		ull k = 1;
		for (i=0;i<len1;i++)
			k *= p;
		ull wh = 0,th = 0;
		for (i=0;i<len1;i++)
		{
			wh = wh * p + w[i] - 'A' + 1;
			th = th * p + t[i] - 'A' + 1;
		}
		int cnt = 0;
		for (i=0;i+len1<=len2;i++)
		{
			if (wh==th)
				cnt++;
			if (i+len1<len2)
				th = th * p + (t[i+len1] - 'A' + 1) - (t[i] - 'A' + 1) * k;
		//例如:w:12303		t:212303 
		//		wh 12303  	p假设就是10,因为hash也是转化为p进制的,p就是10进制中的数量级 
		//		th 21230 	上式中的k为100000,k就是数量级 
		//      假设th 的下一位是3 
		//		th =  21230 * 10 + 3 - 2 * 100000
		//		   = 12303 
		//这一步的意思就是这样,简单说就是去掉第一个字符后面再加上 一个字符,就这样循环下去 
		}
		printf("%d\n",cnt);
 	}
 	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值