KMP
KMP:
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N=1e6+10000+100; 4 int arr[N],nex[N]; 5 int t,n,m,flag; 6 int KMP(){ 7 int j; 8 for(int i=1;i<=n+m+1;i++){ 9 j=nex[i-1]; 10 while(arr[i]!=arr[j]&&j>0){ 11 j=nex[j-1]; 12 } 13 if(arr[i]==arr[j]){ 14 nex[i]=j+1; 15 if(nex[i]==m)return i-2*m+1;//返回的是长串中目标字串的初始位置 16 } 17 } 18 return -1; 19 } 20 21 int main(){ 22 scanf("%d",&t); 23 while(t--){ 24 flag=0; 25 memset(nex,0,sizeof(nex)); 26 cin>>n>>m; 27 for(int i=1;i<=n;i++){ 28 scanf("%d",&arr[i+m]); 29 } 30 arr[m]=N; 31 for(int i=0;i<m;i++){ 32 scanf("%d",&arr[i]); 33 } 34 printf("%d\n",KMP()); 35 36 } 37 return 0; 38 }
HASH:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef unsigned long long ull; 4 typedef long long ll; 5 const ull mod=1e9+7; 6 const ull N=1e6+100; 7 const ull Base=233; 8 char s1[N],s2[N]; 9 ull Hashes[N]; 10 ull Be[N]; 11 int arr1[N]; 12 int arr2[N]; 13 ull gethash(int l,int r){ 14 return (Hashes[r]%mod-(Hashes[l-1]*Be[r-l+1])%mod+mod)%mod; 15 } 16 int main(){ 17 int t,l1,l2,res,n,m,flag; 18 ull ans; 19 cin>>t; 20 while(t--){ 21 res=0,ans=0,flag=-1; 22 scanf("%d %d",&n,&m); 23 for(int i=1;i<=n;i++){ 24 scanf("%d",&arr1[i]); 25 arr1[i]+=N; 26 } 27 for(int j=1;j<=m;j++){ 28 scanf("%d",&arr2[j]); 29 arr2[j]+=N; 30 } 31 Be[0]=1; 32 for(int i=1;i<=n;i++){ 33 Hashes[i]=((Hashes[i-1]*Base%mod)+arr1[i]%mod)%mod; 34 Be[i]=Be[i-1]*Base%mod; 35 } 36 for(int i=1;i<=m;i++){ 37 ans=(ans*Base%mod+arr2[i])%mod; 38 } 39 for(int i=1;i+m-1<=n;i++){ 40 if(gethash(i,i+m-1)==ans){ 41 flag=i; 42 break; 43 } 44 } 45 printf("%d\n",flag); 46 } 47 }