Fu_L's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Fu-L/cp-library

:heavy_check_mark: z_algorithm
(src/string/z_algorithm.hpp)

z_algorithm

(1) vector<int> z_algorithm(string s)
(2) vector<int> z_algorithm(vector<T> s)

s の長さを $n$ として,長さ $n$ の配列 z を返します.
z[i] = LCP(s, s[i, n)) です.
(LCPとは,Longest Common Prefix (先頭から何文字一致しているか) の略です.)

計算量

Depends on

Verified with

Code

#pragma once
#include "../template/template.hpp"
template <typename T>
vector<int> z_algorithm(const vector<T>& s) {
    const int n = (int)s.size();
    if(n == 0) return {};
    vector<int> z(n);
    z[0] = 0;
    for(int i = 1, j = 0; i < n; ++i) {
        int& k = z[i];
        k = (j + z[j] <= i) ? 0 : min(j + z[j] - i, z[i - j]);
        while(i + k < n and s[k] == s[i + k]) ++k;
        if(j + z[j] < i + z[i]) j = i;
    }
    z[0] = n;
    return z;
}
vector<int> z_algorithm(const string& s) {
    const int n = (int)s.size();
    vector<int> s2(n);
    for(int i = 0; i < n; ++i) {
        s2[i] = s[i];
    }
    return z_algorithm(s2);
}
#line 2 "src/template/template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<long long, long long>;
#define rep(i, a, b) for(long long i = (a); i < (b); ++i)
#define rrep(i, a, b) for(long long i = (a); i >= (b); --i)
constexpr long long inf = 4e18;
struct SetupIO {
    SetupIO() {
        ios::sync_with_stdio(0);
        cin.tie(0);
        cout << fixed << setprecision(30);
    }
} setup_io;
#line 3 "src/string/z_algorithm.hpp"
template <typename T>
vector<int> z_algorithm(const vector<T>& s) {
    const int n = (int)s.size();
    if(n == 0) return {};
    vector<int> z(n);
    z[0] = 0;
    for(int i = 1, j = 0; i < n; ++i) {
        int& k = z[i];
        k = (j + z[j] <= i) ? 0 : min(j + z[j] - i, z[i - j]);
        while(i + k < n and s[k] == s[i + k]) ++k;
        if(j + z[j] < i + z[i]) j = i;
    }
    z[0] = n;
    return z;
}
vector<int> z_algorithm(const string& s) {
    const int n = (int)s.size();
    vector<int> s2(n);
    for(int i = 0; i < n; ++i) {
        s2[i] = s[i];
    }
    return z_algorithm(s2);
}
Back to top page