forked from mrsac7/CSES-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2107 - String Functions.cpp
More file actions
59 lines (52 loc) · 1.33 KB
/
2107 - String Functions.cpp
File metadata and controls
59 lines (52 loc) · 1.33 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// String Functions
//
// Problem name: String Functions
// Problem Link: https://cses.fi/problemset/task/2107
// Author: Bernardo Archegas (https://codeforces.com/profile/Ber)
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
mt19937 rng((int) chrono::steady_clock::now().time_since_epoch().count());
const int MOD = 1e9 + 7;
const int MAXN = 1e5 + 5;
const ll INF = 2e18;
vector<int> pi(string s) {
int n = (int)s.length();
vector<int> pi(n);
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
vector<int> z(string s) {
int n = (int) s.length();
vector<int> z(n);
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = min (r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}
return z;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
string s;
cin >> s;
vector<int> vpi = pi(s), vz = z(s);
for (int x : vz) cout << x << ' ';
cout << '\n';
for (int x : vpi) cout << x << ' ';
cout << '\n';
return 0;
}