Crazy Search
题意:求由nc个字母组成的长串中有多少长度为n的不同子串
将原串看成nc进制的数,分别求出长度为n的串的哈希值之后统计出不同的哈希值数即可。
1 #include <cstring> 2 #include <iostream> 3 #include <cstdio> 4 using namespace std; 5 #define CLR(m,a) memset(m,a,sizeof(m)) 6 const int maxn=16000010; 7 int val[128]; 8 int ha[maxn]; 9 int n,nc; 10 char s[1000010]; 11 int main() 12 { 13 while(scanf("%d%d",&n,&nc)!=EOF){ 14 CLR(val,0); 15 CLR(ha,0); 16 int cnt=0; 17 scanf("%s",s); 18 for(int i=0;s[i];i++){ 19 if(!val[s[i]]) val[s[i]]=cnt++; 20 if(cnt==nc) break; 21 } 22 int ans=0; 23 for(int i=0;s[i+n-1];i++){ 24 int hashval=0; 25 for(int j=i;j<i+n;j++){ 26 hashval=hashval*nc+val[s[j]]; 27 } 28 if(!ha[hashval]){ 29 ha[hashval]=1; 30 ans++; 31 } 32 } 33 printf("%d ",ans); 34 } 35 36 }