-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSequenceHash.cpp
More file actions
32 lines (26 loc) · 811 Bytes
/
SequenceHash.cpp
File metadata and controls
32 lines (26 loc) · 811 Bytes
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
struct SequenceHash
{
vector<long long> prefixHash, powers;
SequenceHash(const vector<int>& seq)
{
int L = seq.size();
prefixHash.resize(L+1); powers.resize(L+1);
prefixHash[0] = 0LL; powers[0] = 1LL;
for(int i = 1; i <= L;i++)
{
prefixHash[i] = prefixHash[i-1] * 31LL + seq[i-1];
powers[i] = powers[i-1] * 31LL;
}
}
long long hash(int a, int b) // Returns hash code for seq[a..b], both endpoints inclusive
{
return prefixHash[b+1] - prefixHash[a] * powers[b-a+1];
}
};
int main()
{
//Example usage
int A[] = { 1, 2, 3, 1, 2, 3};
SequenceHash sh(VI(A)); // Just instantiate the SequenceHash
assert( sh.hash(0,2) == sh.hash(3,5));
}