Skip to content

Commit bfce419

Browse files
committed
RollingHash on Strings/Vector<int> added
1 parent da09b2d commit bfce419

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Library/Miscellanious/RollingHash.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
5+
typedef long long HashInt;
6+
static const HashInt HASH_MOD = 2'000'000'033;
7+
struct ModBasedHashInt {
8+
HashInt x; ModBasedHashInt(HashInt x=0) : x(x) {}
9+
ModBasedHashInt operator+(ModBasedHashInt o) {
10+
HashInt y = x + o.x;
11+
return y - (y >= HASH_MOD) * HASH_MOD;
12+
}
13+
ModBasedHashInt operator*(ModBasedHashInt o) { return x*o.x % HASH_MOD; }
14+
HashInt operator-(ModBasedHashInt o) {
15+
HashInt y = x - o.x;
16+
return y + (y < 0) * HASH_MOD;
17+
}
18+
};
19+
struct RollingHash {
20+
#define sz(x) ((int)x.size())
21+
vector<ModBasedHashInt> hash, power;
22+
HashInt C;
23+
RollingHash(string& str, HashInt Co) : hash(sz(str)+1), power(hash) {
24+
C = Co;
25+
power[0] = 1;
26+
for(int i=0; i<sz(str); i++) {
27+
hash[i+1] = hash[i] * C + str[i];
28+
power[i+1] = power[i] * C;
29+
}
30+
}
31+
32+
HashInt get(int l, int r) { // hash [l, r)
33+
return hash[r] - hash[l] * power[r - l];
34+
}
35+
};

0 commit comments

Comments
 (0)