首页 > 其他分享 >这个hash我也不会(Crazy Search )

这个hash我也不会(Crazy Search )

时间:2023-03-08 16:32:21浏览次数:48  
标签:Crazy hash int text Search number substrings 字符串 size


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.

Input


The first line of input consists of two numbers, N and NC, separated by exactly one space. This is followed by the text where the search takes place. You may assume that the maximum number of substrings formed by the possible set of characters does not exceed 16 Millions.

Output


The program should output just an integer corresponding to the number of different substrings of size N found in the given text.

Sample Input


3 4 daababac

Sample Output


5

Hint


Huge input,scanf is recommended.


大概意思就是:第一行N,M,第二行一个字符串。M代表下面的字符串有M种字母,N代表N长度的子字符串。求这个字符串有多少个不一样的N长度的子字符串。

思路大体上是有的:将这个字符串的每个子字符串转换成M进制的数,然后看看一共有多少个不同的数。写了代码就是WA!无语。。。。

WA代码具体如下:

#include<cstdio>
#include<cstring>
#include<cmath>
char str[16000005];
bool hash[16000005];
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
scanf("%s",str);
int i;
int sum=0;
int len=strlen(str);
for(i=n-1;i<len;i++)
{
int s=i;
int flag=3;
int temp=0;
while(flag--)
temp+=(int)pow(k,n-flag-1)*(str[s--]-97);
if(hash[temp])
continue;
sum++;
hash[temp]=true;
}
printf("%d\n",sum);
}
return 0;
}

标签:Crazy,hash,int,text,Search,number,substrings,字符串,size
From: https://blog.51cto.com/u_15998011/6108468

相关文章