Skip to content

Commit 042d188

Browse files
committed
add string hashing
1 parent 226ac27 commit 042d188

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

library/strings/string_hash.hpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#pragma once
2+
//! https://codeforces.com/blog/entry/4898#comment-157965
3+
//! - use random base to avoid getting hacked on codeforces
4+
//! - work mod 1e9+7 if birthday paradox is not a problem
5+
//! @time O(n + q)
6+
//! @space O(n)
7+
using mint = array<ll, 2>;
8+
constexpr mint mod = {ll(1e9 + 7), ll(1e9 + 9)};
9+
const ll base = 239017;
10+
struct str_hash {
11+
vector<mint> ha, pw;
12+
str_hash(const auto& s): ha(sz(s) + 1), pw(ha) {
13+
pw[0] = {1, 1};
14+
rep(i, 0, sz(s)) rep(j, 0, 2) {
15+
pw[i + 1][j] = pw[i][j] * base % mod[j];
16+
ha[i + 1][j] = (ha[i][j] * base + s[i] + 1) % mod[j];
17+
}
18+
}
19+
mint subarray(int l, int r) { // [l, r)
20+
mint res;
21+
rep(j, 0, 2) {
22+
res[j] = ha[r][j] - ha[l][j] * pw[r - l][j] % mod[j];
23+
if (res[j] < 0) res[j] += mod[j];
24+
}
25+
return res;
26+
}
27+
};
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#define PROBLEM \
2+
"https://judge.yosupo.jp/problem/zalgorithm"
3+
#include "../template.hpp"
4+
#include "../../../library/strings/string_hash.hpp"
5+
int main() {
6+
cin.tie(0)->sync_with_stdio(0);
7+
string s;
8+
cin >> s;
9+
int n = sz(s);
10+
str_hash hash(s);
11+
for (int i = 0; i < n; i++) {
12+
int start = i, end = n + 1;
13+
while (start + 1 < end) {
14+
int mid = (start + end) / 2;
15+
int len = mid - i;
16+
if (hash.subarray(i, mid) == hash.subarray(0, len))
17+
start = mid;
18+
else end = mid;
19+
}
20+
cout << start - i << ' ';
21+
}
22+
cout << '\n';
23+
return 0;
24+
}

0 commit comments

Comments
 (0)