Description
Many people like to solve hard puzzles some of which may lead them to madness. One such puzzle could be finding a hidden prime number in a given text. Such number could be the number of different substrings of a given size that exist in the text. As you soon will discover, you really need the help of a computer and a good algorithm to solve such a puzzle.
Your task is to write a program that given the size, N, of the substring, the number of different characters that may occur in the text, NC, and the text itself, determines the number of different substrings of size N that appear in the text.
As an example, consider N=3, NC=4 and the text “daababac”. The different substrings of size 3 that can be found in this text are: “daa”; “aab”; “aba”; “bab”; “bac”. Therefore, the answer should be 5.
【题目分析】
用哈希的方法,把一个字符串每一位当做一个小于base的数,然后把它看做base进制下的数。然后映射到一个数组上进行查询和统计。更多的时候,可能会用到取模来取地址,所以说,数组越大越不容易出错。是哈希中比较简单的一道题目
【代码】
#include <cstdio>
#include <cstring>
char ch[16000000];
int chh[255];
bool hash[16000000];
int main()
{
int n,base,ans=0;
scanf("%d%d",&n,&base);
scanf("%s",ch);
int cnt=0,l=strlen(ch)-1;
for (int i=0;i<=l;++i) if (!chh[ch[i]]) chh[ch[i]]=++cnt;
for (int i=0;i<=l-n+1;++i)
{
int sum=0;
for (int j=i;j<n+i;++j)
sum*=base,sum+=chh[ch[j]];
if (!hash[sum]) ans++,hash[sum]=true;
}
printf("%d\n",ans);
}