这个题我之前用kmp板子写过一次,这次开始学习哈希,再上一个单哈希的方法,就当入门模板吧。
###思路:
算出子字符串的哈希值,然后遍历主字符串枚举起点,算出和相同长度子串的哈希值,如果值相同则答案加1。
代码如下:
#include<iostream>
#include<cstdio>
#include<fstream>
#include<set>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<iomanip>
#include<cstdlib>
#include<list>
#include<queue>
#include<stack>
#include<algorithm>
#define inf 0x3f3f3f3f
#define MOD 1000000007
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define meminf(a) memset(a,inf,sizeof(a))
#define HASHP 13331;//加了一个哈希公式中的p,据说13331很玄学?反正作为萌新先用着看看
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
char w[10010],T[1000100];
ull hash1[10010],hash2[1000100],xp[10010];
void init()
{
xp[0]=1;
for(int i=1;i<=10000;i++)xp[i]=xp[i-1]*13331;
}
int make_hash(char *s,ull *hash)//逆序构造单哈希数组
{
int len=strlen(s);
hash[len]=0;
for(int i=len-1;i>=0;i--)hash[i]=hash[i+1]*13331+s[i]-'A'+1;
return len;
}
int get_hash(char *s,ull *hash,int qi,int l)//计算子字符串哈希值
{
return hash[qi]-hash[qi+l]*xp[l];
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0);
/* freopen("test.txt","r",stdin);
freopen("output.txt","w",stdout);*/
int t;
cin>>t;
init();//初始化Xp数组
while(t--)
{
cin>>w>>T;
//主要是为了初始化出两个字符串的前缀哈希数组
int lenw=make_hash(w,hash1);
int lent=make_hash(T,hash2);
ull hashw=hash1[0];//目标子串的哈希值
int count=0;//答案
for(int i=0;i<=lent-lenw;i++)//枚举子字符串起点
{
ull hasht=get_hash(T,hash2,i,lenw);//算出子串哈希值
if(hasht==hashw)count++;
}
cout<<count<<endl;
}
}