最近看了下字符串哈希的算法,学习了大佬的博客,这里小结一下。
顺便附上大佬博客的链接,方便日后回顾。
哈希:
我的理解是将字符当作某一进制的数来看,这样相同的字符串就会有一样的值,不相同的字符串的值就不同。但值得注意的是这个进制必须大于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