hdu-1711(hash)
题意:给你T组数据,每组数据分别输入n,m和长度为n的数字数组,和长度为m的数字数组,问你长度为m的数组第一次出现在长度为n的数组的位置
解题思路:标准字符串匹配问题,一般用kmp解,拿来练hash
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> using namespace std; typedef long long ll; const ll mod=1e9+7; const ll p=133331; const int M=1e6+100; const int N=1e4+100; ll h[M]; ll a[N],b[M]; ll lena,lenb,t,n,m; ll pp[N]; ll juage(ll l,ll r) { ll tmp=(h[r]-(h[l-1]*pp[r-l+1])%mod)%mod; while(tmp<0) tmp+=mod; return tmp; } int main() { cin>>t; while(t--) { memset(h,0,sizeof(h)); cin>>m>>n; ll ans=0; pp[0]=1; for(int i=1;i<=n;i++) pp[i]=(pp[i-1]*p)%mod; for(int i=1;i<=m;i++) { cin>>b[i];b[i]+=1000000; h[i]=(h[i-1]*p+b[i])%mod; } for(int i=1;i<=n;i++) { cin>>a[i];a[i]+=1000000; ans=(ans*p+a[i])%mod; } int sc=-1; for(int i=1;i<=m;i++) { if((i+n-1)>m) break; else { // cout<<i<<" "<<i+n-1<<" "<<juage(i,i+n-1)<<endl; if(juage(i,i+n-1)==ans) { sc=i;break; } } } cout<<sc<<endl; } }