add rolling hash snippet

This commit is contained in:
Code Lich 2025-04-23 14:49:24 +07:00
parent ae7968f066
commit ee1189f090
1 changed files with 25 additions and 0 deletions

View File

@ -216,4 +216,29 @@ ls.add_snippets('cpp', {
'};', '};',
} }
), ),
s('rollinghash', {
t {
'struct RollingHash {',
' using ll = long long;',
' ll base, mod;',
' vector<ll> power;',
' vector<ll> prefix_hash;',
' RollingHash(const string &s, ll base, ll mod) : base(base), mod(mod) {',
' int n = s.size();',
' power.resize(n + 1, 1);',
' prefix_hash.resize(n + 1, 0);',
' for (int i = 0; i < n; ++i) {',
' power[i + 1] = (__int128)power[i] * base % mod;',
' prefix_hash[i + 1] = ((__int128)prefix_hash[i] * base + s[i]) % mod;',
' }',
' }',
' ll get_hash(int l, int r) {',
' ll hash_r = prefix_hash[r + 1];',
' ll hash_l = (__int128)prefix_hash[l] * power[r - l + 1] % mod;',
' ll res = (hash_r - hash_l + mod) % mod;',
' return res;',
' }',
'};',
},
}),
}) })