模拟赛当天,YZR大佬告诉我可以用HASH来做KMP,然后当场没做出来,今天正好没事干,打了个HASH试试看,结果真把KMP的题给过了
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 const int Bas = 131, M = 1e6 + 10; 6 char a[M],b[M]; 7 long long la,lb; 8 long long sumv[M],mil[M],key; 9 long long get(long long l,long long r) 10 { 11 return sumv[r]-sumv[l]*mil[la]; 12 } 13 int main() 14 { 15 key=0; 16 memset(sumv,0,sizeof sumv); 17 scanf("%s%s",b+1,a+1); 18 la=strlen(a+1),lb=strlen(b+1),mil[0]=1; 19 for (int i=1;i<=la;++i) key=key*Bas+(int)a[i]; 20 for (int i=1;i<=lb;++i) 21 sumv[i]=sumv[i-1]*Bas+(int)b[i],mil[i]=mil[i-1]*Bas; 22 int ans=0; 23 for (int i=0;i<=lb-la;++i) 24 if (key==get(i,i+la)) ++ans; 25 cout<<ans<<endl; 26 return 0; 27 }