cp-library

競技プログラミング用 C++ ライブラリ

View the Project on GitHub qandori/cp-library

:heavy_check_mark: Z algorithm

string/z_algorithm.hpp · GitHub で見る

共通ページ

#include "lib/string/z_algorithm.hpp"

auto z = z_algorithm("ababa"); // {5,0,3,0,1}
auto a = z_algorithm(std::vector<int>{1, 2, 1, 2}); // {4,0,2,0}

z_algorithm(sequence) は、各位置からの接尾辞と列全体との最長共通接頭辞の長さを vector<int> で返します。非空列では z[0]=sequence.size()、空列では空配列です。

string_view、vector<T>、span<const T> を渡せます。T は等値比較が可能とし、vector<bool> は対象外です。列長は INT_MAX 以下とします。

列長を \(n\) として、時間・追加空間は \(O(n)\) です。

依存ライブラリ

検証コード

コード

#ifndef STRING_Z_ALGORITHM_HPP
#define STRING_Z_ALGORITHM_HPP

#include "../components/sequence_match.hpp"
#include <cassert>
#include <limits>
#include <span>
#include <string_view>
#include <vector>

template <class T>
std::vector<int> z_algorithm(std::span<const T> sequence) {
	assert(sequence.size() <= std::size_t(std::numeric_limits<int>::max()));
	std::vector<int> result(sequence.size());
	sequence_match_detail::Matcher<T> match(sequence);
	sequence_match_detail::z_table(int(sequence.size()), result.data(), [&](int a, int b, int limit) { return match.forward(a, b, limit); });
	return result;
}

inline std::vector<int> z_algorithm(std::string_view sequence) {
	return z_algorithm(std::span<const char>(sequence.data(), sequence.size()));
}

template <class T, class Allocator>
std::vector<int> z_algorithm(const std::vector<T, Allocator> &sequence) {
	return z_algorithm(std::span<const T>(sequence.data(), sequence.size()));
}

#endif
Back to top page