版本比较
字符串哈希和碰撞概率
正文
增加 42 行删除 34 行
2 行未改动34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515215 行未改动686970717273747576777812 行未改动9192939495969798999 行未改动2 行未改动字符串哈希就是一种进制哈希、多项式哈希。一般来说,模数会选择一个很大的质数,进制的基数会选择一个小于模数的跟字符集差不多大小的质数。双哈希带质数模数(快速计算子串哈希值)```cppconst int B[] = {131, 233}, MOD[] = {(int)1e9 + 7, 998244353};struct Hash {vector<int> h[2], b[2];void init(const string &s) {for (int x : {0, 1}) {h[x].assign(s.size() + 1, 0);b[x].assign(s.size() + 1, 0);}b[0][0] = b[1][0] = 1;for (int i = 0; i < s.size(); i++) {for (int x : {0, 1}) {h[x][i + 1] = (1ll * h[x][i] * B[x] + s[i]) % MOD[x];b[x][i + 1] = 1ll * b[x][i] * B[x] % MOD[x];}}}pair<int, int> get_hash(int l, int r) {int res[2];for (int x : {0, 1}) {res[x] = ((h[x][r] - 1ll * b[x][r - l + 1] * h[x][l - 1]) % MOD[x] + MOD[x]) % MOD[x];}return {res[0], res[1]};}} T;```计算字符串哈希值```cppint str_hash(string s){int res = 0,base = 13331,mod = 1000000009;for(int i = 0;s[i];++i) res = (res * base + s[i]) % mod;return res;}```单哈希带质数模数(快速计算子串哈希值)```cppstruct Hash{15 行未改动};```单 Hash 自然溢出法(可快速计算子串)(不推荐使用,CF 题目是会卡该算法的)```cppstruct Hash{int base = 13331;vector<int> h,p;12 行未改动}};```## 碰撞概率参考:1. http://rng-58.blogspot.com/2017/02/hashing-and-probability-of-collision.html9 行未改动2 行未改动34567891011121314151617181920212215 行未改动3839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858612 行未改动991001011021031041051061079 行未改动2 行未改动字符串哈希就是一种进制哈希、多项式哈希。一般来说,模数会选择一个很大的质数,进制的基数会选择一个小于模数的跟字符集差不多大小的质数。## 计算字符串哈希值```cppint str_hash(string s){int res = 0,base = 13331,mod = 1000000009;for(int i = 0;s[i];++i) res = (res * base + s[i]) % mod;return res;}```## 单哈希带质数模数(快速计算子串哈希值)```cppstruct Hash{15 行未改动};```## 双哈希带质数模数(快速计算子串哈希值)```cpp#include <bits/stdc++.h>using namespace std;const int K = 2;using H = array<int, K>;const H B = {233, 131}, MOD = {998244353, (int)1e9 + 7};struct Hash {int n;vector<H> b; // 进制基数的 i 次方vector<H> pre; // 前缀哈希值void init(const string &s) {this->n = s.size();b.assign(n + 1, H{});pre.assign(n + 1, H{});b[0].fill(1);for (int i = 0; i < n; i++) {for (int x = 0; x < K; x++) {b[i + 1][x] = 1ll * b[i][x] * B[x] % MOD[x];pre[i + 1][x] = (1ll * pre[i][x] * B[x] + s[i]) % MOD[x];}}}H get_hash(int l, int r) {H res;for (int x = 0; x < K; x++) {res[x] = (pre[r][x] - 1ll * pre[l - 1][x] * b[r - l + 1][x] % MOD[x] + MOD[x]) % MOD[x];}return res;}};```## 单 Hash 自然溢出法(可快速计算子串)(不推荐使用,CF 题目是会卡该算法的)```cppstruct Hash{int base = 13331;vector<int> h,p;12 行未改动}};```# 碰撞概率参考:1. http://rng-58.blogspot.com/2017/02/hashing-and-probability-of-collision.html9 行未改动