Description
给出两个字符串W和T,求T中有几个W子串。
Input
第一行为数据数.
每组数据有两行W和T,表示模式串和原始串.
Output
对每组数据,每行一个数,表示匹配数.
Sample Input
3 BAPC BAPC AZA AZAZAZA VERDI AVERDXIVYERDIAN
Sample Output
1 3 0
字符串hash算法:
1、预处理b^n;(注意b要求是质数,最好大一点,本题我一般选133)
2、计算主串的hash表,
3、计算匹配串的hash值
4、枚举起点为i长度为n的子串,判断匹配串是否匹配。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
typedef unsigned long long ULL;
const int maxn = 1001000;
ULL sum[maxn],power[maxn],tmp,b=133;
char s1[maxn],s2[maxn];
int main(void)
{
int n,m,j,i,ans,k;
power[0]=1;
for(i=1;i<maxn;i++) power[i]=power[i-1]*b;
while(~scanf("%d",&k))
{
while(k--)
{
scanf("%s%s",s1+1,s2+1);
n=strlen(s1+1),m=strlen(s2+1);
sum[0]=0;
for(i=1;i<=m;i++) sum[i]=sum[i-1]*b+(ULL)(s2[i]-'A');
tmp=0;
for(i=1;i<=n;i++) tmp=tmp*b+(ULL)(s1[i]-'A');
ans=0;
for(i=0;i<=m-n;i++)
if(tmp==sum[i+n]-power[n]*sum[i]) ans++;
printf("%d\n",ans);
}
}
return 0;
}