双哈希
POJ3461
#include<bits/stdc++.h>
#define ull unsigned long long
using namespace std;
const int maxn=1e6+10;
const int mo=1e9+9;
const int p=1331;
ull hs1[maxn],hs2[maxn],p1[maxn],p2[maxn];
ull hw1,hw2;
void init()
{
p1[0]=1;
p2[0]=1;
for (int i=1;i<=10000;i++)
{
p1[i]=p1[i-1]*p;
p2[i]=p2[i-1]*p%mo;
}
}
ull get1(int l,int r) {return hs1[r]-hs1[l-1]*p1[r-l+1];}
ull get2(int l,int r) {return (hs2[r]-hs2[l-1]*p2[r-l+1]%mo+mo)%mo;}
int main()
{
int T;
cin >> T;
init();
while (T--)
{
string w,t;
hw1=hw2=0;
memset(hs1,0,sizeof(hs1));
memset(hs2,0,sizeof(hs2));
string put1,put2;
cin >> put1;
w=" "+put1;
cin >> put2;
t=" "+put2;
int lenw=put1.size();
int lent=put2.size();
for (int i=1;i<=lenw;i++)
{
hw1=hw1*p+w[i];
hw2=(hw2*p%mo+w[i])%mo;
}
for (int i=1;i<=lent;i++)
{
hs1[i]=hs1[i-1]*p+t[i];
hs2[i]=(hs2[i-1]*p%mo+t[i])%mo;
}
int ans=0;
for (int l=1;l+lenw-1<=lent;l++)
{
int r=l+lenw-1;
if (hw1 == get1(l,r) && hw2 == get2(l,r)) ans++;
}
cout << ans << endl;
}
return 0;
}
$\frak{msjing}$

浙公网安备 33010602011771号