Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- std::vector<int> PrefixFunction(const std::string& s) {
- std::vector<int> pi(s.size());
- for (int i = 1; i < s.size(); ++i) {
- for (int j = pi[i - 1]; j > 0; j = pi[j - 1]) {
- if (s[i] == s[j]) {
- pi[i] = j + 1;
- break;
- }
- }
- if (pi[i] == 0 && s[i] == s[0]) pi[i] = 1;
- }
- return pi;
- }
- int main0() {
- std::string s;
- std::cin >> s;
- std::vector<int> pi = PrefixFunction(s);
- for (int v : pi) std::cout << v << " ";
- std::cout << std::endl;
- return 0;
- }
- std::vector<int> ZFunction(const std::string& s) {
- std::vector<int> z(s.size());
- z[0] = s.size();
- int l = 0, r = 0;
- for (int i = 1; i < s.size(); ++i) {
- if (i < r) {
- z[i] = std::min(r - i, z[i - l]);
- }
- while (i + z[i] < s.size() && s[z[i]] == s[i + z[i]]) ++z[i];
- if (i + z[i] > r) {
- l = i;
- r = i + z[i];
- }
- }
- return z;
- }
- int main() {
- std::string s;
- std::cin >> s;
- std::vector<int> pi = ZFunction(s);
- for (int v : pi) std::cout << v << " ";
- std::cout << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement