字符串hash模板题 P5018

Description

给出两个字符串W和T,求T中有几个W子串


Input

第一行为数据组数.


每组数据有两行W和T,表示模式串和原始串


Output

对每组数据,每行一个数,表示匹配数.


Hint

1 ≤ |W| ≤ 10,000 (here |W| denotes the length of the string W). |W| ≤ |T| ≤ 1,000,000.


Solution

这道题跟KMP的那道题是一样的然后是用字符串hash来做,优点是优化了时间复杂度。这里用的字符串hash模的是264,因为是字符,取模足够大,不会产生冲突的情况。264也就是长整型,为了让计算机自然溢出达到取模的目的定义数组和sumb的时候要用unsigned long long,从而不会溢出负数。字符串hash的关键是找到匹配的条件,也就是h[i+n-1]-h[i-1]*power[n]==sumb时可以匹配。


注意事项:
1、读入字符的时候如果是从S+1和T+1读入的话h[0]和sumb就只用初始化为0,如果是从S和T读入的话就要初始化成S[i]-'A'+1和T[i]-'A'+1。
2、关系式是从i+n-1到i-1,乘power的时候只需要乘子串长度的set好的b
3、b要取大一点。。。oj上的测试数据太骚了。。。。。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define ull unsigned long long
#define maxn 1000005
#define maxm 10005
using namespace std;
char S[maxn],T[maxm];
ull power[maxn],h[maxn],sumb;
int n,m,cnt,num;
void init(){
	scanf("%s",T+1);
	scanf("%s",S+1);
	cnt=0;
}
void setb(int b){
	m=strlen(S+1),n=strlen(T+1);
	power[0]=1;
	for(int i=1;i<=m;i++){
		power[i]=power[i-1]*b;
	}
}
void sethash(){
	h[0]=0;
	for(int i=1;i<=m;i++){
		h[i]=h[i-1]*10003+S[i]-'A'+1;
	}
}
void setT(){
	sumb=0;
	for(int i=1;i<=n;i++){
		sumb=sumb*10003+T[i]-'A'+1;
	}
}
void findhash(){
	for(int i=1;i+n-1<=m;i++){
		if(h[i+n-1]-h[i-1]*power[n]==sumb)cnt++;
	}
}
int main(){
	scanf("%d",&num);
	for(int i=1;i<=num;i++){
		init();
		setb(10003);
	    sethash();
	    setT();
	    findhash();
	    printf("%d
",cnt);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/virtual-north-Illya/p/10045060.html