Hash 算法(A - Crazy Search)

Hash 算法入门(A - Crazy Search)

我相信 ,喜欢看电影,玩游戏的同学们,肯定知道下载完进行数据检测的过程,实际上这就是哈希算法的应用,也就是说,把一整个数据优化成更简的MD5码。有人可能会问能不能把MD5码转为原数据呢?要是你能做出来的话,我代表人类感谢你。

不过hash有点麻烦,而且有点困难,这次我从简单的字符转换讲吧,什么哈希冲突的,等我学的更多的时候补上吧。

  1. 我们直接怼一个题吧

    A - Crazy Search POJ - 1200

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

那么我们如何做呢?

我们在这里可以把这个字母字符串变成一串数字串,然后每一个字符串分站由一个值构成,如果有相同的,不累加,如果没相同的则累加。

你可能会问,如果有不同的字符串,有一样的字母,但有不同的排序怎么办呢?

很简单,那就把位置也作为转化依据。

#include<cstdio>
#include<cstring>
using namespace std;
int a,b;
char c[160000000];
int hash[9999];			//保存转化字符
bool array[160000000];   //判断f值是否重复
int main(){
	while(scanf("%d %d",&a,&b)!=EOF){
			getchar();
		scanf("%s",&c);
		int d=strlen(c);
		int e=0;
		for(int i=0;i<d;i++){
			if(hash[c[i]]==0){  //将每个字符转化为c个数字,也可以看作c进制
				hash[c[i]]=e++;
			}
		}
		int sum=0;
		for(int x=0;x<=d-a;x++){   
			int f=0;
			for(int y=x;y<x+a;y++){    
				f=f*b+hash[c[y]];    //这里是转化十进制的过程,同时请注意f*b,这是避免有一样的字母,但有不同的排序的关键
			}
			if(!array[f]){     //利用bool来判断是否存在。
				sum++;
				array[f]=true;
			}
		}
		printf("%d\n",sum);
	}
	return 0;
} 

这里只是hash的起步题,本人小蒟蒻,只能慢慢的学习了。

如果有那个那个大佬讲的好,欢迎留言让我康康。o(〃^▽^〃)o

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值