-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhash.cpp
More file actions
42 lines (34 loc) · 1.03 KB
/
hash.cpp
File metadata and controls
42 lines (34 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int MAXN = 1e6 + 5;
const ll MOD = 1e9 + 7; //WA? Muda o MOD e a base
const ll base = 153;
ll expb[MAXN];
void precalc(){
expb[0] = 1;
for(int i=1; i<MAXN; i++)
expb[i] = (expb[i-1]*base)%MOD;
}
struct StringHash{
vector<ll> hsh;
StringHash(string &s){
hsh.assign(s.size()+1, 0);
for(int i=0; i<s.size(); i++)
hsh[i+1] = (hsh[i] * base % MOD + s[i]) % MOD;
}
ll gethash(int l, int r){
return (MOD + hsh[r+1] - hsh[l]*expb[r-l+1] % MOD ) % MOD;
}
};
/******************************************************
String Hash
precalc() -> O(N)
StringHash() -> O(|S|)
gethash() -> O(1)
StringHash hash(s); -> Cria uma struct de StringHash para a string s
hash.gethash(l, r); -> Retorna o hash do intervalo L R da string (0-Indexado)
IMPORTANTE! Chamar precalc() no início do código
const ll MOD = 131'807'699; -> Big Prime Number
const ll base = 127; -> Random number larger than the Alphabet
*******************************************************/