hash也是一种字符串算法,哈希算法在生活中无处不在,被誉为统治世界的十大算法。hash是指 将任意长度的输入通过hash算法转化为固定长度的输出。它是一个对字符串单向加密的过程。
hash算法具有以下特点:
- 不可逆:不能通过hash值计算出原值
- 效率高:能够快速得到结果
- 冲突少:这正是hash不断追求的
常常应用于:信息安全领域以及验证文件完整性
最简单最常用的hash算法:BKDR_hash
通过hash函数,将字符串看作一串base进制的数转化为一串便于比较的10进制数。这是一个映射的过程,不同的字符串对应不同的hash值。
得到的hash值可能会很大,所以要取模。
但是取模意味着,不同的字符串可能会得到相同的hash值。就比如对2取模,只要3个hash值,就必定出现重复。这就是hash冲突。假设取模为mod,两个未取mod的hash值,mod+1和1,取模后就会重复。
为了尽可能避免冲突,mod尽可能取大一点。最大位2^64.ull
base进制的选取:根据概率统计,进制取131,1331,13331,,,,时,冲突是比较少的。(很神奇) 无论取多少,都要大于所有字符对应数字的最大值。就像10进制,某一进制位不可能为11,不然就进位了。
如果出现了hash冲突,怎么办:
- 核实一下,如果两个字符串hash值相等,就比较两个字符串,时间为O(m)。
- 多hash,一个字符串有多个不同算法的hash值。
- 布隆过滤。
我不知道
P3370 【模板】字符串哈希https://www.luogu.com.cn/problem/P3370
计算机对于大于ull的数自动取模,因此直接上ull
C语言代码实现
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
unsigned long long base=1331;
unsigned long long shift[10000+5];
char str[10000+5];
unsigned long long hashh(char *str)
{
int len=strlen(str);
unsigned long long ans=0;
for(int i=0;i<len;i++)
{
ans=ans*base+(unsigned long long)str[i];
}
return ans;
}
void Quick_sort(unsigned long long *arr,int begin,int end)
{
if(begin>=end)
{
return;
}
int i=begin;int j=end;
while(i!=j)
{
while(arr[j]>=arr[begin]&&j>i)
{
j--;
}
while(arr[i]<=arr[begin]&&i<j)
{
i++;
}
unsigned long long temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
unsigned long long temp=arr[begin];
arr[begin]=arr[i];
arr[i]=temp;
Quick_sort(arr,begin,i-1);
Quick_sort(arr,i+1,end);
}
int main()
{
int N;
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%s",str);
shift[i]=hashh(str);
}
Quick_sort(shift,0,N-1);
int ans=1;
for(int i=0;i<N-1;i++)
{
if(shift[i]!=shift[i+1])
{
ans++;
}
}
printf("%d",ans);
return 0;
}