http://acm.hdu.edu.cn/showproblem.php?pid=1711
把数组前缀hash成b进制数
具体原理zzy解释的很清楚:https://blog.csdn.net/qq_42129242/article/details/99431737
1 #define bug(x) cout<<#x<<" is "<<x<<endl 2 #define IO std::ios::sync_with_stdio(0) 3 #include <bits/stdc++.h> 4 #define iter ::iterator 5 #define pa pair<int,int> 6 using namespace std; 7 #define ll long long 8 #define mk make_pair 9 #define pb push_back 10 #define se second 11 #define fi first 12 #define ls o<<1 13 #define rs o<<1|1 14 const int N=1e6+5; 15 ll m1=1e9+7,m2=998244353; 16 ll b1=1e6+97,b2=1e6+83; 17 int T,n,m; 18 ll a[N][3]; 19 ll cal(ll x,ll y,ll mod){ 20 ll res=1; 21 while(y){ 22 if(y&1)res=res*x%mod; 23 x=x*x%mod; 24 y>>=1; 25 } 26 return res; 27 } 28 int main(){ 29 scanf("%d",&T); 30 while(T--){ 31 scanf("%d%d",&n,&m); 32 ll h1=0,h2=0; 33 for(int i=1;i<=n;i++){ 34 ll x; 35 scanf("%lld",&x); 36 h1=(h1*b1+x)%m1; 37 h2=(h2*b2+x)%m2; 38 a[i][1]=h1; 39 a[i][2]=h2; 40 } 41 h1=0,h2=0; 42 for(int i=1;i<=m;i++){ 43 ll x; 44 scanf("%lld",&x); 45 h1=(h1*b1+x)%m1; 46 h2=(h2*b2+x)%m2; 47 } 48 int ans=-1; 49 for(int i=m;i<=n;i++){ 50 int f=0; 51 if((a[i][1]-a[i-m][1]*cal(b1,m,m1)%m1+m1)%m1==h1)f++; 52 if((a[i][2]-a[i-m][2]*cal(b2,m,m2)%m2+m2)%m2==h2)f++; 53 if(f==2){ 54 ans=i-m+1; 55 break; 56 } 57 } 58 printf("%d ",ans); 59 } 60 } 61 /* 62 100 63 5 3 64 1 2 3 4 5 65 2 3 4 66 */