Oulipo(暴力-字符串哈希hash)

Oulipo(暴力-字符串哈希hash)

judge:POJ 3461

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:

http://poj.org/problem?id=3461

Input

http://poj.org/problem?id=3461

Output

http://poj.org/problem?id=3461

Sample Input

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN

Sample Output

1
3
0

题意

给你两个字符串,问你第一个串在第二个串中出现几次(不同出现的地方可以重叠)

分别求两个串的哈希值,O(n)匹配即可。

代码
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstdio>
#include <cstring>
#define _for(i, a) for(int i = 0; i < (a); i++)
#define _rep(i, a, b) for(int i = (a); i <= (b); i++)
typedef unsigned long long ull;
const int maxn = 10005;
const int maxm = 1000005;
const int inf = 0x3f3f3f3f;
ull mod = 133;
using namespace std;

char a[maxn], b[maxm];
ull p[maxm], hs[maxm];

ull gethash(int l, int r) {
	return hs[r] - hs[l - 1] * p[r - l + 1];
}

int main() {
	p[0] = 1;
	_rep(i, 1, maxm - 1) p[i] = p[i - 1] * mod;

	int T;
	cin >> T;
	while (T--) {
		scanf("%s%s", a + 1, b + 1);
		ull a1 = 0;
		int alen = strlen(a + 1),
			blen = strlen(b + 1);
		_rep(i, 1, alen) {
			a1 = a1 * mod + (ull)a[i];
		}
		hs[0] = 0;
		_rep(i, 1, blen) {
			hs[i] = hs[i - 1] * mod + (ull)b[i];
		}
		int ans = 0;
		_rep(i, 1, blen - alen + 1) {
			if (a1 == gethash(i, i + alen - 1)) {
				ans++;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值