字符串哈希 模板

这篇博客介绍了字符串哈希算法在解决竞赛问题中的应用,特别是针对雪糕形状的判断。通过哈希函数,可以有效地比较两个雪糕是否具有相同的臂长,从而找出可能相同的雪糕对。博客中提到了哈希冲突的处理,并给出了相关资源链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看了下字符串哈希的算法,学习了大佬的博客,这里小结一下。
顺便附上大佬博客的链接,方便日后回顾。

  1. 字符串哈希函数总结
  2. wiki oi—字符串哈希
  3. 如何解决哈希冲突—暴雪的哈希算法

哈希:
我的理解是将字符当作某一进制的数来看,这样相同的字符串就会有一样的值,不相同的字符串的值就不同。但值得注意的是这个进制必须大于128,而且为减少哈希冲突,需要构建不同的哈希函数。

记录下我学的在竞赛中比较实用的一种,因为好记且比较短。


// BKDR Hash Function
unsigned int get_hash(const  string s)
{
   
	unsigned int res = 0;//哈希的结果
	unsigned int base = 131;//将字符串当作131进制的数
	for (int i = 0; i < s.length(); i++)
	{
   
		res = res * base + s[i];
	}
	return res&0x7fffffff;//与运算,使得所得结果为int
}

在这里插入图片描述

栗子:

Snowflake 题目描述
You may have heard that no two snowflakes are alike. Your task is to write a program to determine whether this is really true. Your program will read information about a collection of snowflakes, and search for a pair that may be identical. Each snowflake has six arms. For each snowflake, your program will be provided with a measurement of the length of each of the six arms. Any pair of snowflakes which have the same lengths of corresponding arms should be flagged by your program as possibly identical.
输入描述:
The first line of input will contain a single integer n, 0 < n ≤ 100000, the number of snowflakes to follow. This will be followed by n lines, each describing a snowflake. Each snowflake will be described by a line containing six integers (each integer is at least 0 and less than 10000000), the lengths of the arms of the snow ake. The lengths of the arms will be given in order around the snowflake (either clock

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值