競技プログラミング用の C++ ライブラリ
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// AhoCorasick を、文字列を愚直に比べる実装とランダムに比較する
// 同じパターンを複数回追加する場合や、文字の種類が少なくて重なりが多い場合も試す
// 問題の入力は使わず、すべて一致したら Hello World を出力する
#include "../../../src/string/aho-corasick.hpp"
#include <algorithm>
#include <forward_list>
#include <iostream>
#include <random>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "../../../src/utility/range.hpp"
#if __cplusplus >= 202002L
#include <ranges>
#endif
bool ok = true;
void check(bool cond, const char* what) {
if (!cond) {
if (ok) std::cerr << "failed: " << what << std::endl;
ok = false;
}
}
int main() {
std::mt19937 rng(314);
for (int rep = 0; rep < 3000 && ok; rep++) {
int sigma = rng() % 3 + 1;
auto random_string = [&](int max_len) {
std::string s(rng() % max_len + 1, 'a');
for (char& c : s) c = 'a' + rng() % sigma;
return s;
};
int m = rng() % 6 + 1;
std::vector<std::string> pats;
AhoCorasick<3, 'a'> ac;
for (int i = 0; i < m; i++) {
std::string p = !pats.empty() && rng() % 4 == 0 ? pats[rng() % pats.size()] : random_string(4);
pats.push_back(p);
check(ac.add(p) == i, "add の番号");
}
ac.build();
check(ac.pattern_count() == m, "pattern_count");
// ノードの構造: 各ノードの文字列を親からたどって作り、失敗リンク・遷移・match_count を確かめる
std::vector<std::string> str(ac.size());
for (long long v = 1; v < ac.size(); v++) {
long long p = ac.parent(v);
check(0 <= p && p < v, "親は先に作られている");
for (int c = 0; c < 3; c++) {
if (ac.next(p, 'a' + c) == v) str[v] = str[p] + static_cast<char>('a' + c);
}
check(ac.depth(v) == static_cast<long long>(str[v].size()), "depth");
}
check(ac.parent(0) == -1 && ac.link(0) == -1 && ac.depth(0) == 0, "根");
auto find_node = [&](const std::string& s) -> long long {
for (long long v = 0; v < ac.size(); v++) {
if (str[v] == s) return v;
}
return -1;
};
for (int i = 0; i < m; i++) check(str[ac.node(i)] == pats[i], "node");
for (long long v = 0; v < ac.size(); v++) {
const std::string& s = str[v];
// 失敗リンク: ノードのある最長の真の接尾辞
if (v > 0) {
long long expect = 0;
for (size_t len = s.size() - 1; len > 0; len--) {
long long u = find_node(s.substr(s.size() - len));
if (u != -1) {
expect = u;
break;
}
}
check(ac.link(v) == expect, "link");
}
// 遷移: s + c の接尾辞のうち、ノードのある最長のもの
for (int c = 0; c < 3; c++) {
std::string t = s + static_cast<char>('a' + c);
long long expect = 0;
for (size_t len = t.size(); len > 0; len--) {
long long u = find_node(t.substr(t.size() - len));
if (u != -1) {
expect = u;
break;
}
}
check(ac.next(v, 'a' + c) == expect, "next");
}
long long mc = 0;
for (const auto& p : pats) mc += p.size() <= s.size() && s.compare(s.size() - p.size(), p.size(), p) == 0;
check(ac.match_count(v) == mc, "match_count");
}
// 照合: 愚直に全位置で比べる
for (int t = 0; t < 5; t++) {
std::string text = rng() % 5 == 0 ? std::string() : random_string(30);
std::vector<long long> each(m, 0);
std::vector<decltype(ac)::Match> all; // (開始位置, 番号)
std::vector<std::tuple<long long, long long, long long>> order; // (終わる位置, -長さ, 番号) の順に並べる
for (long long end = 1; end <= static_cast<long long>(text.size()); end++) {
for (int i = 0; i < m; i++) {
long long len = pats[i].size();
if (len <= end && text.compare(end - len, len, pats[i]) == 0) {
each[i]++;
order.emplace_back(end, -len, i);
}
}
}
std::sort(order.begin(), order.end());
for (auto [end, neg_len, i] : order) all.push_back({end + neg_len, i});
long long total = 0;
for (long long x : each) total += x;
check(ac.count(text) == total, "count");
check(ac.count_each(text) == each, "count_each");
const auto matches = ac.find_all(text);
check(std::vector<decltype(ac)::Match>(matches.begin(), matches.end()) == all, "find_all");
}
}
// std::vector<int> の文字列と、別の文字の範囲
{
AhoCorasick<10, 0> ac;
ac.add(std::vector<int>{1, 2});
ac.add(std::vector<int>{2});
ac.build();
std::vector<int> text = {1, 2, 2, 1, 2};
check(ac.count(text) == 5 && ac.count_each(text) == std::vector<long long>{2, 3}, "std::vector<int>");
const auto matches = ac.find_all(text);
check(std::vector<decltype(ac)::Match>(matches.begin(), matches.end()) ==
std::vector<decltype(ac)::Match>{{0, 0}, {1, 1}, {2, 1}, {3, 0}, {4, 1}},
"std::vector<int> の列挙");
}
// 一致の順序、独立した走査、右辺値の所有、コピー・移動後の寿命。
{
AhoCorasick<> ac;
ac.add(std::string("a"));
ac.add(std::string("aa"));
ac.add(std::string("a"));
ac.build();
using Match = decltype(ac)::Match;
const std::vector<Match> expected = {{0, 0}, {0, 2}, {0, 1}, {1, 0}, {1, 2}};
auto make_matches = [&] { return ac.find_all(std::string("aa")); };
const auto matches = make_matches();
auto copy = matches;
auto moved = std::move(copy);
for (int rep = 0; rep < 2; rep++) {
check(std::vector<Match>(matches.begin(), matches.end()) == expected, "右辺値と繰り返し走査");
check(std::vector<Match>(moved.begin(), moved.end()) == expected, "range のコピー・移動");
}
auto it = matches.begin(), independent = it;
check(*it++ == expected[0] && *it == expected[1] && *independent == expected[0], "iterator のコピーと後置 increment");
long long pairs = 0;
for (auto x : matches) {
for (auto y : matches) pairs += x.id == y.id;
}
check(pairs == 9, "入れ子の走査");
std::forward_list<char> text = {'a', 'a'};
const auto linked = ac.find_all(text);
check(std::vector<Match>(linked.begin(), linked.end()) == expected, "非ランダムアクセス入力");
auto empty = ac.find_all(std::string());
check(empty.begin() == empty.end(), "空の入力");
#if __cplusplus >= 202002L
static_assert(std::ranges::input_range<decltype(matches)>);
#endif
}
// デフォルト構築できない iterator も受け取れる。
{
AhoCorasick<3, 0> ac;
ac.add(std::vector<int>{0, 1});
ac.build();
const auto matches = ac.find_all(Range(3));
check(std::vector<decltype(ac)::Match>(matches.begin(), matches.end()) ==
std::vector<decltype(ac)::Match>{{0, 0}},
"Range の入力");
}
// 入力のコピーを要求せず、最初の一致より後を読まない。
{
struct Character {
long long* reads;
operator int() const {
++*reads;
return 'a';
}
};
struct Text {
std::vector<Character> chars;
explicit Text(long long* reads) : chars(100, Character{reads}) {}
Text(const Text&) = delete;
auto begin() const { return chars.begin(); }
auto end() const { return chars.end(); }
};
AhoCorasick<> ac;
ac.add(std::string("a"));
ac.build();
long long reads = 0;
Text text(&reads);
const auto matches = ac.find_all(text);
check(reads == 0, "構築時は入力を読まない");
for (auto match : matches) {
check(match.pos == 0 && match.id == 0, "最初の一致");
break;
}
check(reads == 1, "途中終了");
}
{
AhoCorasick<> ac;
ac.build();
const auto matches = ac.find_all(std::string("aaa"));
check(matches.begin() == matches.end(), "パターンなし");
}
if (ok) std::cout << "Hello World" << std::endl;
}#line 1 "test/unittest/string/aho-corasick.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// AhoCorasick を、文字列を愚直に比べる実装とランダムに比較する
// 同じパターンを複数回追加する場合や、文字の種類が少なくて重なりが多い場合も試す
// 問題の入力は使わず、すべて一致したら Hello World を出力する
#line 2 "src/string/aho-corasick.hpp"
/**
* @file aho-corasick.hpp
* @brief Aho-Corasick
*/
#include <array>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <optional>
#include <type_traits>
#include <utility>
#include <vector>
/**
* @brief Aho-Corasick (複数のパターンの照合)
*
* パターンを add で追加してから build を呼ぶ。文字 c は c - Base として 0 以上 K 未満の番号に直す
* ノードは Trie と同じく、文字列を追加した順に作った番号を持つ。根はノード 0 (空文字列)
* 例:
* AhoCorasick<26, 'a'> ac;
* ac.add("he");
* ac.add("she");
* ac.build();
* ac.count("ushers"); // 2 ("she" と "he")
*
* @tparam K 文字の種類数
* @tparam Base 最小の文字
*/
template <int K = 26, int Base = 'a'>
class AhoCorasick {
struct Node {
std::array<int, K> next; // build 前は Trie の子 (なければ -1)、build 後は文字を読んだときの遷移先
int parent, depth;
int link; // 失敗リンク (このノードの文字列の、最長の真の接尾辞のノード)
int out; // 失敗リンクをたどって最初に着く、パターンが終わるノード (なければ -1)
int head; // このノードで終わるパターンの番号のリストの先頭 (なければ -1)
int match_count; // このノードの文字列の接尾辞になっているパターンの個数
};
// メモリを抑えるため、ノードの中身は int で持つ。外へ返すときに long long にする
std::vector<Node> nodes;
std::vector<int> pattern_node, next_pattern; // パターンの終わるノードと、同じノードで終わる次のパターン
std::vector<int> bfs_order;
bool built = false;
int add_node(int parent, int depth) {
Node node;
node.next.fill(-1);
node.parent = parent;
node.depth = depth;
node.link = 0;
node.out = node.head = -1;
node.match_count = 0;
nodes.push_back(node);
return nodes.size() - 1;
}
static int index(int c) {
assert(0 <= c - Base && c - Base < K);
return c - Base;
}
public:
AhoCorasick() { add_node(-1, 0); }
/**
* @brief パターン s を追加し、パターンの番号 (追加した順に 0, 1, ...) を返す O(|s|)
* 空でない文字列に限る。同じパターンを何度も追加でき、別のパターンとして数える
* @param s std::string や std::vector<int> など、要素を整数に変換できる列
*/
template <typename R>
long long add(const R& s) {
assert(!built);
assert(std::begin(s) != std::end(s));
int v = 0;
for (auto c : s) {
int i = index(c);
if (nodes[v].next[i] == -1) {
int u = add_node(v, nodes[v].depth + 1);
nodes[v].next[i] = u;
}
v = nodes[v].next[i];
}
int id = pattern_node.size();
pattern_node.push_back(v);
next_pattern.push_back(nodes[v].head);
nodes[v].head = id;
return id;
}
/**
* @brief 失敗リンクと遷移を作る。パターンを追加し終えてから 1 回だけ呼ぶ O(K * ノード数)
*/
void build() {
assert(!built);
built = true;
for (int v = 0; v < static_cast<int>(nodes.size()); v++) {
// 同じノードで終わるパターンのリストを、追加した順に並べ直す
int rev = -1;
for (int id = nodes[v].head; id != -1;) {
int nx = next_pattern[id];
next_pattern[id] = rev;
rev = id;
id = nx;
nodes[v].match_count++;
}
nodes[v].head = rev;
}
bfs_order.reserve(nodes.size());
bfs_order.push_back(0);
for (int i = 0; i < static_cast<int>(bfs_order.size()); i++) {
int v = bfs_order[i];
for (int c = 0; c < K; c++) {
int u = nodes[v].next[c];
// まだ -1 なら Trie の子はない。失敗リンク先からの遷移を使う
if (u == -1) {
nodes[v].next[c] = v == 0 ? 0 : nodes[nodes[v].link].next[c];
continue;
}
int l = v == 0 ? 0 : nodes[nodes[v].link].next[c];
nodes[u].link = l;
nodes[u].out = nodes[l].head != -1 ? l : nodes[l].out;
nodes[u].match_count += nodes[l].match_count;
bfs_order.push_back(u);
}
}
}
/**
* @brief ノードの個数 (根を含む)
*/
long long size() const { return nodes.size(); }
/**
* @brief パターンの個数
*/
long long pattern_count() const { return pattern_node.size(); }
/**
* @brief パターン i が終わるノード
*/
long long node(long long i) const {
assert(0 <= i && i < pattern_count());
return pattern_node[i];
}
/**
* @brief ノード v の親 (根なら -1)
*/
long long parent(long long v) const { return nodes[v].parent; }
/**
* @brief ノード v の深さ (対応する文字列の長さ)
*/
long long depth(long long v) const { return nodes[v].depth; }
/**
* @brief ノード v の失敗リンク (v の文字列の最長の真の接尾辞のうち、ノードのあるもの)。根なら -1
*/
long long link(long long v) const {
assert(built);
return v == 0 ? -1 : nodes[v].link;
}
/**
* @brief ノード v で文字 c を読んだときに移るノード
*/
long long next(long long v, int c) const {
assert(built);
return nodes[v].next[index(c)];
}
/**
* @brief ノード v の文字列の接尾辞になっているパターンの個数 (v に着いたときに終わるパターンの個数)
*/
long long match_count(long long v) const {
assert(built);
return nodes[v].match_count;
}
/**
* @brief text に現れるパターンの個数の合計 (同じパターンが何回現れても、すべて数える) O(|text|)
*/
template <typename R>
long long count(const R& text) const {
assert(built);
long long res = 0;
int v = 0;
for (auto c : text) {
v = nodes[v].next[index(c)];
res += nodes[v].match_count;
}
return res;
}
/**
* @brief パターンごとに、text に現れる回数を返す O(|text| + ノード数 + パターン数)
*/
template <typename R>
std::vector<long long> count_each(const R& text) const {
assert(built);
std::vector<long long> visit(nodes.size());
int v = 0;
for (auto c : text) {
v = nodes[v].next[index(c)];
visit[v]++;
}
// 失敗リンクの木で、葉の方から回数を足し上げる
for (int i = static_cast<int>(bfs_order.size()) - 1; i > 0; i--) {
int u = bfs_order[i];
visit[nodes[u].link] += visit[u];
}
std::vector<long long> res(pattern_node.size());
for (int i = 0; i < static_cast<int>(pattern_node.size()); i++) res[i] = visit[pattern_node[i]];
return res;
}
/**
* @brief find_all が返す、パターンが現れた位置
*/
struct Match {
long long pos; //!< 開始位置
long long id; //!< パターンの番号
friend bool operator==(const Match& a, const Match& b) { return a.pos == b.pos && a.id == b.id; }
friend bool operator!=(const Match& a, const Match& b) { return !(a == b); }
};
private:
template <typename R>
class Matches {
const AhoCorasick* ac;
R text;
using Text = std::remove_reference_t<R>;
using TextIterator = decltype(std::begin(std::declval<const Text&>()));
using TextSentinel = decltype(std::end(std::declval<const Text&>()));
public:
Matches(const AhoCorasick* ac, R&& text) : ac(ac), text(std::forward<R>(text)) {}
class iterator {
const AhoCorasick* ac = nullptr;
// 終端 iterator は入力を持たない。入力 iterator のデフォルト構築は要求しない。
std::optional<TextIterator> cursor;
std::optional<TextSentinel> stop;
long long pos = 0;
int v = 0, u = -1, id = -1;
public:
using value_type = Match;
using difference_type = std::ptrdiff_t;
using reference = value_type;
using pointer = void;
using iterator_category = std::input_iterator_tag;
iterator() = default;
iterator(const AhoCorasick* ac, TextIterator cursor, TextSentinel stop) : ac(ac), cursor(cursor), stop(stop) { ++*this; }
value_type operator*() const { return {pos - ac->nodes[u].depth, id}; }
iterator& operator++() {
if (id != -1) {
id = ac->next_pattern[id];
if (id != -1) return *this;
u = ac->nodes[u].out;
if (u != -1) {
id = ac->nodes[u].head;
return *this;
}
}
while (*cursor != *stop) {
v = ac->nodes[v].next[index(**cursor)];
++*cursor;
++pos;
u = ac->nodes[v].head != -1 ? v : ac->nodes[v].out;
if (u != -1) {
id = ac->nodes[u].head;
break;
}
}
return *this;
}
iterator operator++(int) {
auto previous = *this;
++*this;
return previous;
}
bool operator==(const iterator& other) const {
if (id == -1 || other.id == -1) return id == other.id;
return ac == other.ac && pos == other.pos && id == other.id;
}
bool operator!=(const iterator& other) const { return !(*this == other); }
};
iterator begin() const { return iterator(ac, std::begin(std::as_const(text)), std::end(std::as_const(text))); }
iterator end() const { return iterator(); }
};
public:
/**
* @brief 一致を Match {pos, id} として遅延列挙する。全走査 O(|text| + 出力の個数)、列挙状態は O(1)
* 終了位置の昇順。同じ終了位置なら長さの降順、同じ長さならパターン番号の昇順
* 左辺値の text は参照し、右辺値は所有する
* @pre 走査が終わるまで、このオートマトンと参照する入力を有効なまま保持すること
*/
template <typename R>
auto find_all(R&& text) const {
assert(built);
return Matches<R>(this, std::forward<R>(text));
}
};
#line 8 "test/unittest/string/aho-corasick.test.cpp"
#include <algorithm>
#include <forward_list>
#include <iostream>
#include <random>
#include <string>
#include <tuple>
#line 17 "test/unittest/string/aho-corasick.test.cpp"
#line 2 "src/utility/range.hpp"
/**
* @file range.hpp
* @brief Python の range のような整数列と、その直積の Grid
*/
#line 15 "src/utility/range.hpp"
struct Range {
public:
using value_type = long long;
using const_reference = value_type;
using size_type = long long;
using difference_type = std::ptrdiff_t;
const value_type start;
const value_type stop;
const value_type step;
private:
const value_type norm_stop;
constexpr static value_type normalize(value_type _start, value_type _stop, value_type _step) {
assert(_step != 0);
if (_step > 0) {
if (_start >= _stop) {
return _start;
} else {
return _start + (_stop - _start + _step - 1) / _step * _step;
}
} else {
if (_start <= _stop) {
return _start;
} else {
return _start - (_start - _stop - _step - 1) / _step * _step;
}
}
}
constexpr Range(value_type _start, value_type _stop, value_type _step, value_type _norm_stop)
: start(_start), stop(_stop), step(_step), norm_stop(_norm_stop) {
}
public:
/**
* @brief start から stop の手前まで step ずつ進む整数列
* @pre step != 0
*/
constexpr Range(value_type _start, value_type _stop, value_type _step)
: start(_start), stop(_stop), step(_step), norm_stop(normalize(_start, _stop, _step)) {
}
constexpr Range(value_type _start, value_type _stop)
: start(_start), stop(_stop), step(1), norm_stop(normalize(_start, _stop, 1)) {}
explicit constexpr Range(value_type _stop)
: start(0), stop(_stop), step(1), norm_stop(normalize(0, _stop, 1)) {}
constexpr Range()
: start(0), stop(0), step(1), norm_stop(0) {
}
constexpr Range(const Range& o) = default;
Range& operator=(const Range& o) = delete;
struct const_iterator {
public:
using difference_type = Range::difference_type;
using value_type = Range::value_type;
using pointer = void;
using reference = Range::const_reference;
using iterator_category = std::random_access_iterator_tag;
private:
value_type first = 0, stop = 0, step = 1, value = 0;
constexpr bool same_range(const const_iterator& o) const noexcept {
return first == o.first && stop == o.stop && step == o.step;
}
public:
constexpr const_iterator() noexcept = default;
constexpr const_iterator(const Range& range, value_type value) noexcept
: first(range.start), stop(range.stop), step(range.step), value(value) {}
constexpr reference base() const noexcept {
return value;
}
constexpr const_iterator& operator++() noexcept {
value += step;
return *this;
}
constexpr const_iterator operator++(int) noexcept {
const_iterator ret(*this);
value += step;
return ret;
}
constexpr const_iterator& operator+=(difference_type _n) noexcept {
value += _n * step;
return *this;
}
constexpr friend const_iterator operator+(const const_iterator& i, difference_type _n) noexcept {
const_iterator ret(i);
ret += _n;
return ret;
}
constexpr friend const_iterator operator+(difference_type _n, const const_iterator& i) noexcept {
const_iterator ret(i);
ret += _n;
return ret;
}
constexpr const_iterator& operator--() noexcept {
value -= step;
return *this;
}
constexpr const_iterator operator--(int) noexcept {
const_iterator ret(*this);
value -= step;
return ret;
}
constexpr const_iterator& operator-=(difference_type _n) noexcept {
value -= _n * step;
return *this;
}
constexpr friend const_iterator operator-(const const_iterator& i, difference_type _n) noexcept {
const_iterator ret(i);
ret -= _n;
return ret;
}
constexpr reference operator[](difference_type i) const noexcept { return value + i * step; }
constexpr reference operator*() const noexcept {
return value;
}
constexpr friend bool operator!=(const const_iterator& a, const const_iterator& b) noexcept {
return !a.same_range(b) || a.value != b.value;
}
constexpr friend bool operator==(const const_iterator& a, const const_iterator& b) noexcept {
return !(a != b);
}
constexpr friend bool operator<(const const_iterator& a, const const_iterator& b) noexcept {
assert(a.same_range(b));
return a.step > 0 ? a.value < b.value : a.value > b.value;
}
constexpr friend bool operator>(const const_iterator& a, const const_iterator& b) noexcept { return b < a; }
constexpr friend bool operator<=(const const_iterator& a, const const_iterator& b) noexcept { return !(b < a); }
constexpr friend bool operator>=(const const_iterator& a, const const_iterator& b) noexcept { return !(a < b); }
constexpr friend difference_type operator-(const const_iterator& a, const const_iterator& b) {
assert(a.same_range(b));
if (a.step > 0) {
return (a.value - b.value) / a.step;
} else {
return (b.value - a.value) / (-a.step);
}
}
};
constexpr const_iterator begin() const noexcept {
return {*this, start};
}
constexpr const_iterator end() const noexcept {
return {*this, norm_stop};
}
/**
* @brief x の個数 (0 か 1)
*/
constexpr size_type count(value_type x) const noexcept {
// step がコンパイル時に分からないときも、よく使う step = 1 では割り算をしない
if (step == 1) return start <= x && x < stop;
if (step > 0) {
if (start <= x && x < stop) {
if ((x - start) % step == 0) {
return 1;
}
}
} else {
if (stop < x && x <= start) {
if ((start - x) % (-step) == 0) {
return 1;
}
}
}
return 0;
}
/**
* @brief x が含まれるか
*/
constexpr bool contains(value_type x) const noexcept {
return count(x) != 0;
}
/**
* @brief x のインデックス
* x が含まれないとエラー
*/
constexpr size_type index(value_type x) const {
assert(contains(x));
if (step == 1) return x - start;
return (x - start) / step;
}
/**
* @brief 要素が x のイテレータ
* x が含まれないと end() を返す
*/
constexpr const_iterator find(value_type x) const noexcept {
if (contains(x)) {
return {*this, x};
} else {
return {*this, norm_stop};
}
}
/**
* @brief 要素が x 以上の最小のイテレータ
* step > 0 じゃないとエラー
*/
constexpr const_iterator lower_bound(value_type x) const {
assert(step > 0);
if (norm_stop <= x) {
return end();
} else if (x < start) {
return begin();
} else {
return {*this, start + (x - start + step - 1) / step * step};
}
}
/**
* @brief 要素が x より大きい最小のイテレータ
* step > 0 じゃないとエラー
*/
constexpr const_iterator upper_bound(value_type x) const {
assert(step > 0);
if (norm_stop <= x) {
return end();
} else if (x < start) {
return begin();
} else {
return {*this, start + (x - start + step) / step * step};
}
}
/**
* @brief コンテナの要素数
*/
constexpr size_type size() const noexcept {
if (step > 0) {
return (norm_stop - start) / step;
} else {
return (start - norm_stop) / (-step);
}
}
constexpr value_type at(size_type i) const {
assert(0 <= i && i < size());
return start + i * step;
}
constexpr value_type operator[](size_type i) const {
return at(i);
}
constexpr bool empty() const noexcept {
return start == norm_stop;
}
constexpr value_type sum() const noexcept {
return size() * (norm_stop - step + start) / 2;
}
/**
* @brief 最小値
* 空だとエラー
*/
constexpr value_type min() const {
assert(!empty());
if (step > 0) {
return start;
} else {
return norm_stop - step;
}
}
/**
* @brief 最大値
* 空だとエラー
*/
constexpr value_type max() const {
assert(!empty());
if (step > 0) {
return norm_stop - step;
} else {
return start;
}
}
/**
* @brief 総 xor
* 負を含むとエラー
*/
constexpr value_type product_xor() const noexcept {
if (empty()) return 0;
assert(min() >= 0);
Range sorted_range(sorted());
value_type res = 0;
std::make_unsigned_t<value_type> t = 1;
while (t <= static_cast<std::make_unsigned_t<value_type>>(max())) {
std::make_unsigned_t<value_type> tmp = 0, n = size(), m = t, a = sorted_range.step, b = sorted_range.start;
while (true) {
if (a >= m) {
tmp += n * (n - 1) / 2 * (a / m);
a %= m;
}
if (b >= m) {
tmp += n * (b / m);
b %= m;
}
std::make_unsigned_t<value_type> y_max = a * n + b;
if (y_max < m) break;
n = y_max / m;
b = y_max % m;
std::swap(m, a);
}
if (tmp % 2 == 1) {
res += t;
}
t <<= 1;
}
return res;
}
/**
* @brief 逆順にしたもの
*/
constexpr Range reversed() const noexcept {
return {norm_stop - step, start - step, -step, start - step};
}
/**
* @brief step > 0 だとそのまま step < 0 だと逆順にしたもの
*/
constexpr Range sorted() const noexcept {
if (step > 0) {
return {start, norm_stop, step, norm_stop};
} else {
return {norm_stop - step, start - step, -step, start - step};
}
}
/**
* @brief 要素が [l, r) である範囲を返す
*/
constexpr Range clipped(value_type l, value_type r) const {
if (l >= r) return {};
r--; // 以下では r を含む [l, r] として扱う
if (step > 0) {
value_type _start = [&] {
if (norm_stop <= l) {
return norm_stop;
} else if (l < start) {
return start;
} else {
return start + (l - start + step - 1) / step * step;
}
}();
value_type _stop = [&] {
if (norm_stop <= r) {
return norm_stop;
} else if (r < start) {
return start;
} else {
return start + (r - start + step) / step * step;
}
}();
return {_start, _stop, step, _stop};
} else {
value_type _start = [&] {
if (start - step <= r) {
return start;
} else if (r < norm_stop - step) {
return norm_stop;
} else {
return norm_stop + (r - norm_stop) / step * step;
}
}();
value_type _stop = [&] {
if (start - step <= l) {
return start;
} else if (l < norm_stop - step) {
return norm_stop;
} else {
return norm_stop + (l - norm_stop - 1) / step * step;
}
}();
return {_start, _stop, step, _stop};
}
}
/**
* @brief 要素を Range で指定したコンテナ
*/
constexpr Range slice(const Range& r) const {
if (r.empty()) return {};
if (r.max() < 0) return {};
if (r.min() >= size()) return {};
Range trimmed_range(r.clipped(0, size()));
if (trimmed_range.empty()) return {};
value_type _step = step * trimmed_range.step;
value_type _start = at(trimmed_range.start);
value_type _stop = _start + _step * trimmed_range.size();
return {_start, _stop, _step, _stop};
}
static std::string type_str() {
return "Range";
}
std::string initializer_str() const {
return "{" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + "}";
}
std::string repr() const {
return "Range(" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + ")";
}
std::vector<value_type> to_vector() const {
std::vector<value_type> ret;
ret.reserve(size());
if (step > 0) {
for (value_type x = start; x < stop; x += step) {
ret.push_back(x);
}
} else {
for (value_type x = start; x > stop; x += step) {
ret.push_back(x);
}
}
return ret;
}
constexpr friend bool operator==(const Range& a, const Range& b) noexcept {
if (a.empty() && b.empty()) return true;
if (a.size() != b.size()) return false;
if (a.start != b.start) return false;
if (a.size() == 1) return true;
if (a.step != b.step) return false;
return true;
}
constexpr friend bool operator!=(const Range& a, const Range& b) noexcept {
return !(a == b);
}
};
/**
* @brief 2 つの Range の直積 rows × cols
* (i, j) を i の昇順、同じ i では j の昇順 (行優先) に並べたものとして扱う
*/
struct Grid {
public:
using value_type = std::pair<long long, long long>;
using size_type = long long;
using difference_type = std::ptrdiff_t;
const Range rows;
const Range cols;
private:
const long long width; // cols.size() (index や at で毎回割り算しないように持っておく)
public:
/**
* @brief [0, h) × [0, w)
*/
constexpr Grid(long long h, long long w) : rows(h), cols(w), width(cols.size()) {}
constexpr Grid(const Range& _rows, const Range& _cols) : rows(_rows), cols(_cols), width(cols.size()) {}
constexpr Grid(const Grid& o) = default;
Grid& operator=(const Grid& o) = delete;
struct const_iterator {
public:
using difference_type = Grid::difference_type;
using value_type = Grid::value_type;
using pointer = void;
using reference = value_type;
using iterator_category = std::forward_iterator_tag;
private:
const Grid* rect = nullptr;
long long w = 0; // cols.size()
long long ic = 0; // rows の何番目か
long long jc = 0; // cols の何番目か
public:
constexpr const_iterator() noexcept = default;
constexpr const_iterator(const Grid* _rect, long long _w, long long _ic, long long _jc) noexcept
: rect(_rect), w(_w), ic(_ic), jc(_jc) {}
constexpr value_type operator*() const noexcept {
return {rect->rows.start + ic * rect->rows.step, rect->cols.start + jc * rect->cols.step};
}
constexpr const_iterator& operator++() noexcept {
if (++jc == w) {
jc = 0;
++ic;
}
return *this;
}
constexpr const_iterator operator++(int) noexcept {
const_iterator ret(*this);
++*this;
return ret;
}
constexpr friend bool operator==(const const_iterator& a, const const_iterator& b) noexcept {
return a.ic == b.ic && a.jc == b.jc;
}
constexpr friend bool operator!=(const const_iterator& a, const const_iterator& b) noexcept {
return !(a == b);
}
};
constexpr const_iterator begin() const noexcept {
return {this, width, width == 0 ? rows.size() : 0, 0};
}
constexpr const_iterator end() const noexcept {
return {this, width, rows.size(), 0};
}
/**
* @brief 要素数 rows.size() * cols.size()
*/
constexpr size_type size() const noexcept {
return rows.size() * width;
}
constexpr bool empty() const noexcept {
return rows.empty() || cols.empty();
}
/**
* @brief (i, j) が含まれるか
*/
constexpr bool contains(long long i, long long j) const noexcept {
return rows.contains(i) && cols.contains(j);
}
constexpr bool contains(const value_type& p) const noexcept {
return contains(p.first, p.second);
}
/**
* @brief (i, j) の行優先での位置 (グリッドの頂点番号に使う)
* (i, j) が含まれないとエラー
*/
constexpr size_type index(long long i, long long j) const {
assert(contains(i, j));
return rows.index(i) * width + cols.index(j);
}
constexpr size_type index(const value_type& p) const {
return index(p.first, p.second);
}
/**
* @brief 行優先で k 番目の要素 (index の逆)
*/
constexpr value_type at(size_type k) const {
assert(0 <= k && k < size());
return {rows[k / width], cols[k % width]};
}
constexpr value_type operator[](size_type k) const {
return at(k);
}
private:
// 近傍の方向 (rows・cols の中での位置の差) を Grid の順に並べたもの。先頭 4 つは上下左右だけを並べた別の表
// 4 近傍と 8 近傍の境目が分かるように 2 行に分けているので整形しない
// clang-format off
static constexpr int neighbor_dirs[12][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0},
{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
// clang-format on
public:
/**
* @brief neighbors4 / neighbors8 の戻り値 (範囲 for で使う)
* 作るときに Grid に含まれる方向をビットで持っておき、立っているビットを順に返す
*/
struct Neighbors {
long long i, j, row_step, col_step;
int first; // neighbor_dirs[first + k] がビット k の方向
unsigned mask; // Grid に含まれる方向
struct iterator {
using difference_type = std::ptrdiff_t;
using value_type = Grid::value_type;
using pointer = void;
using reference = value_type;
using iterator_category = std::forward_iterator_tag;
const Neighbors* nb = nullptr;
unsigned rest = 0; // まだ返していない方向
constexpr value_type operator*() const noexcept {
const int k = nb->first + __builtin_ctz(rest);
return {nb->i + neighbor_dirs[k][0] * nb->row_step, nb->j + neighbor_dirs[k][1] * nb->col_step};
}
constexpr iterator& operator++() noexcept {
rest &= rest - 1;
return *this;
}
constexpr iterator operator++(int) noexcept {
iterator ret(*this);
++*this;
return ret;
}
constexpr friend bool operator==(const iterator& a, const iterator& b) noexcept { return a.rest == b.rest; }
constexpr friend bool operator!=(const iterator& a, const iterator& b) noexcept { return a.rest != b.rest; }
};
constexpr iterator begin() const noexcept { return {this, mask}; }
constexpr iterator end() const noexcept { return {this, 0}; }
constexpr long long size() const noexcept { return __builtin_popcount(mask); }
constexpr bool empty() const noexcept { return mask == 0; }
};
private:
constexpr Neighbors neighbors(long long i, long long j, int first, int last) const {
assert(contains(i, j));
unsigned mask = 0;
for (int k = first; k < last; k++) {
if (contains(i + neighbor_dirs[k][0] * rows.step, j + neighbor_dirs[k][1] * cols.step)) mask |= 1u << (k - first);
}
return {i, j, rows.step, cols.step, first, mask};
}
public:
/**
* @brief (i, j) の上下左右のうち Grid に含まれるものを、Grid の順に返す
* 隣は rows・cols の中で隣り合う要素 (i ± rows.step など)。(i, j) が含まれないとエラー
*/
constexpr Neighbors neighbors4(long long i, long long j) const {
return neighbors(i, j, 0, 4);
}
constexpr Neighbors neighbors4(const value_type& p) const {
return neighbors4(p.first, p.second);
}
/**
* @brief (i, j) を囲む 8 つのうち Grid に含まれるものを、Grid の順に返す
*/
constexpr Neighbors neighbors8(long long i, long long j) const {
return neighbors(i, j, 4, 12);
}
constexpr Neighbors neighbors8(const value_type& p) const {
return neighbors8(p.first, p.second);
}
static std::string type_str() {
return "Grid";
}
std::string initializer_str() const {
return "{" + rows.initializer_str() + ", " + cols.initializer_str() + "}";
}
std::string repr() const {
return "Grid(" + rows.repr() + ", " + cols.repr() + ")";
}
constexpr friend bool operator==(const Grid& a, const Grid& b) noexcept {
if (a.empty() && b.empty()) return true;
return a.rows == b.rows && a.cols == b.cols;
}
constexpr friend bool operator!=(const Grid& a, const Grid& b) noexcept {
return !(a == b);
}
};
#line 19 "test/unittest/string/aho-corasick.test.cpp"
#if __cplusplus >= 202002L
#include <ranges>
#endif
bool ok = true;
void check(bool cond, const char* what) {
if (!cond) {
if (ok) std::cerr << "failed: " << what << std::endl;
ok = false;
}
}
int main() {
std::mt19937 rng(314);
for (int rep = 0; rep < 3000 && ok; rep++) {
int sigma = rng() % 3 + 1;
auto random_string = [&](int max_len) {
std::string s(rng() % max_len + 1, 'a');
for (char& c : s) c = 'a' + rng() % sigma;
return s;
};
int m = rng() % 6 + 1;
std::vector<std::string> pats;
AhoCorasick<3, 'a'> ac;
for (int i = 0; i < m; i++) {
std::string p = !pats.empty() && rng() % 4 == 0 ? pats[rng() % pats.size()] : random_string(4);
pats.push_back(p);
check(ac.add(p) == i, "add の番号");
}
ac.build();
check(ac.pattern_count() == m, "pattern_count");
// ノードの構造: 各ノードの文字列を親からたどって作り、失敗リンク・遷移・match_count を確かめる
std::vector<std::string> str(ac.size());
for (long long v = 1; v < ac.size(); v++) {
long long p = ac.parent(v);
check(0 <= p && p < v, "親は先に作られている");
for (int c = 0; c < 3; c++) {
if (ac.next(p, 'a' + c) == v) str[v] = str[p] + static_cast<char>('a' + c);
}
check(ac.depth(v) == static_cast<long long>(str[v].size()), "depth");
}
check(ac.parent(0) == -1 && ac.link(0) == -1 && ac.depth(0) == 0, "根");
auto find_node = [&](const std::string& s) -> long long {
for (long long v = 0; v < ac.size(); v++) {
if (str[v] == s) return v;
}
return -1;
};
for (int i = 0; i < m; i++) check(str[ac.node(i)] == pats[i], "node");
for (long long v = 0; v < ac.size(); v++) {
const std::string& s = str[v];
// 失敗リンク: ノードのある最長の真の接尾辞
if (v > 0) {
long long expect = 0;
for (size_t len = s.size() - 1; len > 0; len--) {
long long u = find_node(s.substr(s.size() - len));
if (u != -1) {
expect = u;
break;
}
}
check(ac.link(v) == expect, "link");
}
// 遷移: s + c の接尾辞のうち、ノードのある最長のもの
for (int c = 0; c < 3; c++) {
std::string t = s + static_cast<char>('a' + c);
long long expect = 0;
for (size_t len = t.size(); len > 0; len--) {
long long u = find_node(t.substr(t.size() - len));
if (u != -1) {
expect = u;
break;
}
}
check(ac.next(v, 'a' + c) == expect, "next");
}
long long mc = 0;
for (const auto& p : pats) mc += p.size() <= s.size() && s.compare(s.size() - p.size(), p.size(), p) == 0;
check(ac.match_count(v) == mc, "match_count");
}
// 照合: 愚直に全位置で比べる
for (int t = 0; t < 5; t++) {
std::string text = rng() % 5 == 0 ? std::string() : random_string(30);
std::vector<long long> each(m, 0);
std::vector<decltype(ac)::Match> all; // (開始位置, 番号)
std::vector<std::tuple<long long, long long, long long>> order; // (終わる位置, -長さ, 番号) の順に並べる
for (long long end = 1; end <= static_cast<long long>(text.size()); end++) {
for (int i = 0; i < m; i++) {
long long len = pats[i].size();
if (len <= end && text.compare(end - len, len, pats[i]) == 0) {
each[i]++;
order.emplace_back(end, -len, i);
}
}
}
std::sort(order.begin(), order.end());
for (auto [end, neg_len, i] : order) all.push_back({end + neg_len, i});
long long total = 0;
for (long long x : each) total += x;
check(ac.count(text) == total, "count");
check(ac.count_each(text) == each, "count_each");
const auto matches = ac.find_all(text);
check(std::vector<decltype(ac)::Match>(matches.begin(), matches.end()) == all, "find_all");
}
}
// std::vector<int> の文字列と、別の文字の範囲
{
AhoCorasick<10, 0> ac;
ac.add(std::vector<int>{1, 2});
ac.add(std::vector<int>{2});
ac.build();
std::vector<int> text = {1, 2, 2, 1, 2};
check(ac.count(text) == 5 && ac.count_each(text) == std::vector<long long>{2, 3}, "std::vector<int>");
const auto matches = ac.find_all(text);
check(std::vector<decltype(ac)::Match>(matches.begin(), matches.end()) ==
std::vector<decltype(ac)::Match>{{0, 0}, {1, 1}, {2, 1}, {3, 0}, {4, 1}},
"std::vector<int> の列挙");
}
// 一致の順序、独立した走査、右辺値の所有、コピー・移動後の寿命。
{
AhoCorasick<> ac;
ac.add(std::string("a"));
ac.add(std::string("aa"));
ac.add(std::string("a"));
ac.build();
using Match = decltype(ac)::Match;
const std::vector<Match> expected = {{0, 0}, {0, 2}, {0, 1}, {1, 0}, {1, 2}};
auto make_matches = [&] { return ac.find_all(std::string("aa")); };
const auto matches = make_matches();
auto copy = matches;
auto moved = std::move(copy);
for (int rep = 0; rep < 2; rep++) {
check(std::vector<Match>(matches.begin(), matches.end()) == expected, "右辺値と繰り返し走査");
check(std::vector<Match>(moved.begin(), moved.end()) == expected, "range のコピー・移動");
}
auto it = matches.begin(), independent = it;
check(*it++ == expected[0] && *it == expected[1] && *independent == expected[0], "iterator のコピーと後置 increment");
long long pairs = 0;
for (auto x : matches) {
for (auto y : matches) pairs += x.id == y.id;
}
check(pairs == 9, "入れ子の走査");
std::forward_list<char> text = {'a', 'a'};
const auto linked = ac.find_all(text);
check(std::vector<Match>(linked.begin(), linked.end()) == expected, "非ランダムアクセス入力");
auto empty = ac.find_all(std::string());
check(empty.begin() == empty.end(), "空の入力");
#if __cplusplus >= 202002L
static_assert(std::ranges::input_range<decltype(matches)>);
#endif
}
// デフォルト構築できない iterator も受け取れる。
{
AhoCorasick<3, 0> ac;
ac.add(std::vector<int>{0, 1});
ac.build();
const auto matches = ac.find_all(Range(3));
check(std::vector<decltype(ac)::Match>(matches.begin(), matches.end()) ==
std::vector<decltype(ac)::Match>{{0, 0}},
"Range の入力");
}
// 入力のコピーを要求せず、最初の一致より後を読まない。
{
struct Character {
long long* reads;
operator int() const {
++*reads;
return 'a';
}
};
struct Text {
std::vector<Character> chars;
explicit Text(long long* reads) : chars(100, Character{reads}) {}
Text(const Text&) = delete;
auto begin() const { return chars.begin(); }
auto end() const { return chars.end(); }
};
AhoCorasick<> ac;
ac.add(std::string("a"));
ac.build();
long long reads = 0;
Text text(&reads);
const auto matches = ac.find_all(text);
check(reads == 0, "構築時は入力を読まない");
for (auto match : matches) {
check(match.pos == 0 && match.id == 0, "最初の一致");
break;
}
check(reads == 1, "途中終了");
}
{
AhoCorasick<> ac;
ac.build();
const auto matches = ac.find_all(std::string("aaa"));
check(matches.begin() == matches.end(), "パターンなし");
}
if (ok) std::cout << "Hello World" << std::endl;
}