可以用KMP写,然而发现hash不用写很长,而且好理解。
定义一个匹配串的hash值为h[m] = c[1]b^ (m - 1) + c[2]b^(m - 2) + …… + c[m - 1]b + c[m],然后向后推的时候h[i] = h[i - 1] - c[i - m] * pow(b,m) + c[i];
然后直接比较在模式串上子串的hash值是不是等于匹配串,是的话就匹配了。
b的选择一般是质数,为了溢出也是正数一般数都定义为usigned long long;
//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define clr(x,y) memset(x,y,sizeof x)
#define PI acos(-1.0)
#define ITER set<int>::iterator
const int Mod = 1e9 + 7;
const int maxn = 1000000 + 10;
const int N = 2;
const ull M = 133;
char s[maxn],t[maxn];
ull p[maxn];
int main()
{
int Tcase;scanf("%d",&Tcase);
while(Tcase --)
{
scanf("%s%s",s,t);int len1 = strlen(s),len2 = strlen(t);
ull ah = 0, bh = 0;ull temp = 1;for(int i = 0; i < len1; i ++)temp *= M;
for(int i = 0;i < len1; i ++)ah = ah * M + s[i],bh = bh * M + t[i];
int ans = 0;
for(int i = len1 - 1; i < len2; i ++)
{
if(bh == ah)ans ++;bh = bh * M - temp * t[i - len1 + 1] + t[i + 1];
}
printf("%d\n",ans);
}
return 0;
}