浅谈字符串哈希

一.分类

1.单模哈希

g(s)=f(s)%mod

注意:①MOD要是质数(使模的结果等概率分布在0~mod-1)②1e9左右不等于1e9+7或1e9+9

2.双模哈希

3.自然溢出(unsigned long long) 

二.比较

  速度 正确率
自然溢出(国内不会卡)(不建议用于POI) 1 2
单模哈希 2 3
双模哈希(绝对安全) 3 1

先给个自然溢出的板子:

#include
#include
#include
#include
using namespace std;
typedef unsigned long long ull;
const int N=1e4+4;
const ull base=263;
int n;
char s[1504];
ull hs[N];
int main() {
    memset(hs,0,sizeof(hs));
    scanf("%d",&n);
    for (int i=1;i<=n;++i) {
        scanf("%s",s+1);
        for (int j=1;s[j];++j)
            hs[i]=hs[i]*base+s[j];
    }
    sort(hs+1,hs+n+1);
    printf("%d\n",unique(hs+1,hs+n+1)-hs-1);
    return 0;
}

 

你可能感兴趣的:(总结,字符串)