由于已经给出字符只有NC种,故可以把子串视为一个NC进制的数,以此构造hash函数就可以了
1 #include <set> 2 #include <map> 3 #include <cmath> 4 #include <queue> 5 #include <vector> 6 #include <cstdio> 7 #include <cstdlib> 8 #include <cstring> 9 #include <iostream> 10 #include <algorithm> 11 using namespace std; 12 const int MAXN=16000001; 13 char s[MAXN];int hash[MAXN],num[130]; 14 int main(){ 15 for(int N,NC;scanf("%d%d",&N,&NC)!=EOF;){ 16 memset(hash,0,sizeof(hash)); 17 memset(num,0,sizeof(num)); 18 scanf("%s",s+1); 19 int cnt=0,ans=0,len=strlen(s+1); 20 for(int i=1;i<=len&&cnt<=NC;i++)if(!num[s[i]])num[s[i]]=cnt++; 21 for(int i=1;i<=len-N+1;i++){ 22 int hashi=0;for(int j=i;j<=i+N-1;j++)hashi=hashi*NC+num[s[j]]; 23 hash[hashi]?0:ans++,hash[hashi]=1; 24 } 25 cout<<ans<<endl; 26 } 27 return 0; 28 }