競技プログラミング用 C++ ライブラリ
test/suffix_automaton_lcs.test.cpp · GitHub で見る
#define PROBLEM "https://judge.yosupo.jp/problem/longest_common_substring"
#include "string/suffix_automaton.hpp"
#include "components/fast_io.hpp"
int main() {
FastInput input;
FastOutput output;
std::string s, t;
input.read(s), input.read(t);
SuffixAutomaton automaton(s);
auto match = automaton.longest_common_substring(t);
output.write(match.text_pos), output.write(' ');
output.write(match.text_pos + match.length), output.write(' ');
output.write(match.query_pos), output.write(' ');
output.println(match.query_pos + match.length);
}
#line 1 "test/suffix_automaton_lcs.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/longest_common_substring"
#line 1 "string/suffix_automaton.hpp"
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <limits>
#include <string_view>
#include <utility>
#include <vector>
class SuffixAutomaton {
struct Node { int length, link, first_end, hits, head; };
struct Edge { int to, next; unsigned char symbol; };
static constexpr int maximum_size = (std::numeric_limits<int>::max() - 1) / 3;
std::vector<Node> nodes_;
std::vector<Edge> edges_;
std::vector<int> prefix_;
std::array<int, 256> root_edges_;
mutable std::vector<std::uint64_t> counts_;
std::uint64_t distinct_ = 0;
int last_ = 0;
void check_([[maybe_unused]] int v) const { assert(0 <= v && v < node_count()); }
int edge_(int v, unsigned char c) const {
if (!v) return root_edges_[c];
for (int e = nodes_[v].head; e != -1; e = edges_[e].next)
if (edges_[e].symbol == c) return e;
return -1;
}
void add_edge_(int v, unsigned char c, int to) {
int e = static_cast<int>(edges_.size());
edges_.push_back({to, nodes_[v].head, c});
nodes_[v].head = e;
if (!v) root_edges_[c] = e;
}
void prepare_counts_() const {
if (!counts_.empty()) return;
auto order = order_by_length();
counts_.resize(nodes_.size());
for (int v = 0; v < node_count(); ++v) counts_[v] = nodes_[v].hits;
for (auto it = order.rbegin(); it != order.rend(); ++it)
if (*it) counts_[nodes_[*it].link] += counts_[*it];
counts_[root] = std::uint64_t(size()) + 1;
}
public:
struct Match { int text_pos = 0, query_pos = 0, length = 0; };
static constexpr int root = 0;
SuffixAutomaton() { clear(); }
explicit SuffixAutomaton(std::string_view s) : SuffixAutomaton() {
assert(s.size() <= std::size_t(maximum_size));
reserve(static_cast<int>(s.size()));
append(s);
}
void clear() {
nodes_.clear(), edges_.clear(), prefix_.clear(), counts_.clear();
nodes_.push_back({0, -1, 0, 0, -1});
root_edges_.fill(-1);
last_ = root, distinct_ = 0;
}
void reserve(int n) {
assert(0 <= n && n <= maximum_size);
nodes_.reserve(std::size_t(n) * 2 + 1);
edges_.reserve(std::size_t(n) * 3 + 1);
prefix_.reserve(n);
}
int size() const { return static_cast<int>(prefix_.size()); }
bool empty() const { return prefix_.empty(); }
int node_count() const { return static_cast<int>(nodes_.size()); }
int last() const { return last_; }
std::uint64_t distinct_count() const { return distinct_; }
int length(int v) const { check_(v); return nodes_[v].length; }
int min_length(int v) const { check_(v); return v ? nodes_[nodes_[v].link].length + 1 : 0; }
int suffix_link(int v) const { check_(v); return nodes_[v].link; }
std::pair<int, int> first_occurrence(int v) const {
check_(v);
return {nodes_[v].first_end - nodes_[v].length, nodes_[v].first_end};
}
int transition(int v, char c) const {
check_(v);
int e = edge_(v, static_cast<unsigned char>(c));
return e == -1 ? -1 : edges_[e].to;
}
std::vector<std::pair<unsigned char, int>> transitions(int v) const {
check_(v);
std::vector<std::pair<unsigned char, int>> result;
for (int e = nodes_[v].head; e != -1; e = edges_[e].next) result.emplace_back(edges_[e].symbol, edges_[e].to);
return result;
}
int push_back(char symbol) {
assert(size() < maximum_size);
counts_.clear();
unsigned char c = static_cast<unsigned char>(symbol);
int cur = node_count(), p = last_, e = -1;
nodes_.push_back({nodes_[last_].length + 1, 0, size() + 1, 1, -1});
while (p != -1 && (e = edge_(p, c)) == -1) {
add_edge_(p, c, cur);
p = nodes_[p].link;
}
if (p != -1) {
int q = edges_[e].to;
if (nodes_[p].length + 1 == nodes_[q].length) nodes_[cur].link = q;
else {
int clone = node_count();
nodes_.push_back({nodes_[p].length + 1, nodes_[q].link, nodes_[q].first_end, 0, -1});
for (int at = nodes_[q].head; at != -1; at = edges_[at].next)
add_edge_(clone, edges_[at].symbol, edges_[at].to);
while (p != -1 && (e = edge_(p, c)) != -1 && edges_[e].to == q) {
edges_[e].to = clone;
p = nodes_[p].link;
}
nodes_[q].link = nodes_[cur].link = clone;
}
}
last_ = cur;
prefix_.push_back(cur);
distinct_ += nodes_[cur].length - nodes_[nodes_[cur].link].length;
return cur;
}
void append(std::string_view s) {
assert(s.size() <= std::size_t(maximum_size - size()));
for (char c : s) push_back(c);
}
int walk(int v, std::string_view s) const {
check_(v);
for (char c : s) { v = transition(v, c); if (v == -1) break; }
return v;
}
int find(std::string_view s) const { return walk(root, s); }
bool contains(std::string_view s) const { return find(s) != -1; }
std::uint64_t count(std::string_view s) const {
int v = find(s);
if (v == -1) return 0;
prepare_counts_();
return counts_[v];
}
std::vector<std::uint64_t> occurrences() const { prepare_counts_(); return counts_; }
const std::vector<int> &prefix_nodes() const { return prefix_; }
std::vector<int> order_by_length() const {
std::vector<int> buckets(std::size_t(size()) + 1), order(nodes_.size());
for (const auto &node : nodes_) ++buckets[node.length];
for (int i = 1; i <= size(); ++i) buckets[i] += buckets[i - 1];
for (int v = node_count() - 1; v >= 0; --v) order[--buckets[nodes_[v].length]] = v;
return order;
}
Match longest_common_substring(std::string_view s) const {
assert(s.size() <= std::size_t(std::numeric_limits<int>::max()));
Match best;
int v = root, matched = 0;
for (int i = 0; i < static_cast<int>(s.size()); ++i) {
int next = transition(v, s[i]);
while (v && next == -1) {
v = nodes_[v].link;
matched = nodes_[v].length;
next = transition(v, s[i]);
}
if (next == -1) { v = root; matched = 0; continue; }
v = next, ++matched;
if (matched > best.length) best = {nodes_[v].first_end - matched, i + 1 - matched, matched};
}
return best;
}
};
#line 1 "components/fast_io.hpp"
#line 6 "components/fast_io.hpp"
#include <bit>
#line 8 "components/fast_io.hpp"
#include <charconv>
#include <cstddef>
#line 11 "components/fast_io.hpp"
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>
#line 17 "components/fast_io.hpp"
#include <type_traits>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace fast_io_detail { struct BulkInput; struct BulkOutput; }
class FastInput {
friend struct fast_io_detail::BulkInput;
static constexpr std::size_t capacity = 1 << 16;
FILE *file = nullptr;
std::unique_ptr<char[]> buffer;
const char *current = "", *end = current;
std::string scratch;
void *mapping = nullptr;
std::size_t mapped_size = 0;
bool refill() {
if (!file) return false;
std::size_t n = std::fread(buffer.get(), 1, capacity, file);
current = buffer.get();
end = current + n;
return n;
}
static const char *scan(const char *p, const char *end) {
while (end - p >= 8) {
std::uint64_t x;
std::memcpy(&x, p, 8);
if ((x - 0x2121212121212121ULL) & ~x & 0x8080808080808080ULL) break;
p += 8;
}
while (p != end && static_cast<unsigned char>(*p) > ' ') ++p;
return p;
}
public:
explicit FastInput(FILE *input = stdin) {
#if defined(__unix__) || defined(__APPLE__)
struct stat status;
int fd = fileno(input);
auto offset = ftello(input);
if (fd >= 0 && offset >= 0 && !fstat(fd, &status) && S_ISREG(status.st_mode) && status.st_size > offset) {
mapped_size = status.st_size;
mapping = mmap(nullptr, mapped_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapping != MAP_FAILED) {
current = static_cast<const char *>(mapping) + offset;
end = static_cast<const char *>(mapping) + mapped_size;
return;
}
mapping = nullptr;
}
#endif
file = input;
buffer = std::make_unique_for_overwrite<char[]>(capacity);
}
explicit FastInput(std::string_view input) : current(input.empty() ? "" : input.data()), end(current + input.size()) {}
FastInput(const FastInput &) = delete;
FastInput &operator=(const FastInput &) = delete;
~FastInput() {
#if defined(__unix__) || defined(__APPLE__)
if (mapping) munmap(mapping, mapped_size);
#endif
}
std::string_view token() {
while (true) {
while (current != end && static_cast<unsigned char>(*current) <= ' ') ++current;
if (current != end) break;
if (!refill()) return {};
}
const char *begin = current;
current = scan(current, end);
if (current != end || !file) return {begin, std::size_t(current - begin)};
scratch.assign(begin, end);
while (refill()) {
current = scan(current, end);
scratch.append(buffer.get(), std::size_t(current - buffer.get()));
if (current != end) break;
}
return scratch;
}
template <class T>
bool read(T &value) {
if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
while (true) {
while (current != end && static_cast<unsigned char>(*current) <= ' ') ++current;
if (current != end) break;
if (!refill()) return false;
}
if constexpr (std::is_unsigned_v<T> && sizeof(T) == 4 && std::endian::native == std::endian::little) {
if (end - current >= 11) {
std::uint64_t x;
std::memcpy(&x, current, 8);
if (!(((x + 0x4646464646464646ULL) | (x - 0x3030303030303030ULL)) & 0x8080808080808080ULL)) {
x &= 0x0f0f0f0f0f0f0f0fULL;
x = (x * 10 + (x >> 8)) & 0x00ff00ff00ff00ffULL;
x = (x * 100 + (x >> 16)) & 0x0000ffff0000ffffULL;
std::uint64_t v = std::uint32_t(x * 10000 + (x >> 32));
int n = 8;
for (; n < 10 && static_cast<unsigned char>(current[n]) - unsigned('0') < 10; ++n)
v = v * 10 + (current[n] - '0');
if (static_cast<unsigned char>(current[n]) <= ' ' && v <= 0xffffffffULL) {
current += n;
value = T(v);
return true;
}
}
}
}
T parsed{};
auto result = std::from_chars(current, end, parsed);
if (result.ec == std::errc{} && (result.ptr != end ? static_cast<unsigned char>(*result.ptr) <= ' ' : !file)) {
current = result.ptr;
value = parsed;
return true;
}
}
auto s = token();
if (s.empty()) return false;
if constexpr (std::is_same_v<T, bool>) {
assert(s == "0" || s == "1");
value = s[0] == '1';
} else if constexpr (std::is_integral_v<T>) {
auto result = std::from_chars(s.data(), s.data() + s.size(), value);
assert(result.ec == std::errc{} && result.ptr == s.data() + s.size());
(void)result;
} else value = T(s);
return true;
}
};
class FastOutput {
friend struct fast_io_detail::BulkOutput;
inline static constexpr auto quads = [] {
std::array<std::array<char, 4>, 10000> table{};
for (int i = 0; i < 10000; ++i)
table[i] = {char('0' + i / 1000), char('0' + i / 100 % 10), char('0' + i / 10 % 10), char('0' + i % 10)};
return table;
}();
FILE *file;
std::unique_ptr<char[]> buffer = std::make_unique_for_overwrite<char[]>(1 << 16);
std::size_t capacity = 1 << 16, length = 0;
char *reserve(std::size_t n) {
if (n > capacity - length) {
if (!flush()) throw std::runtime_error("output failed");
if (n > capacity) {
std::size_t next = std::max(n, 2 * capacity);
buffer = std::make_unique_for_overwrite<char[]>(next);
capacity = next;
}
}
return buffer.get() + length;
}
public:
explicit FastOutput(FILE *output = stdout) : file(output) {}
FastOutput(const FastOutput &) = delete;
FastOutput &operator=(const FastOutput &) = delete;
~FastOutput() { flush(); }
bool flush() {
std::size_t offset = 0;
while (offset < length) {
auto n = std::fwrite(buffer.get() + offset, 1, length - offset, file);
if (!n) {
std::memmove(buffer.get(), buffer.get() + offset, length - offset);
length -= offset;
return false;
}
offset += n;
}
length = 0;
return std::fflush(file) == 0;
}
void write(char c) { *reserve(1) = c; ++length; }
void write(__uint128_t value) {
char digits[40];
char *end = digits + sizeof(digits), *begin = end;
do { *--begin = char('0' + value % 10); value /= 10; } while (value);
write(std::string_view(begin, end - begin));
}
void write(__int128_t value) {
__uint128_t magnitude = __uint128_t(value);
if (value < 0) write('-'), magnitude = 0 - magnitude;
write(magnitude);
}
void write(std::string_view s) {
char *out = reserve(s.size());
if (!s.empty()) std::memcpy(out, s.data(), s.size());
length += s.size();
}
template <class T> requires std::is_integral_v<T>
void write(T value) {
char *out = reserve(32);
if constexpr (std::is_same_v<T, bool>) *out = '0' + value, ++length;
else if constexpr (std::is_unsigned_v<T> && sizeof(T) == 4) {
char *p = out;
if (value >= 100000000) {
auto high = value / 100000000, low = value % 100000000;
p = std::to_chars(p, p + 2, high).ptr;
std::memcpy(p, quads[low / 10000].data(), 4);
std::memcpy(p + 4, quads[low % 10000].data(), 4);
p += 8;
} else if (value >= 10000) {
p = std::to_chars(p, p + 4, value / 10000).ptr;
std::memcpy(p, quads[value % 10000].data(), 4);
p += 4;
} else p = std::to_chars(p, p + 4, value).ptr;
length += p - out;
} else length += std::to_chars(out, out + 32, value).ptr - out;
}
template <class T> requires requires(const T &value, char *out) { value.decimal_capacity(); value.to_chars(out); }
void write(const T &value) {
char *out = reserve(value.decimal_capacity());
length += value.to_chars(out) - out;
}
template <class T>
void println(const T &value) { write(value); write('\n'); }
};
#line 4 "test/suffix_automaton_lcs.test.cpp"
int main() {
FastInput input;
FastOutput output;
std::string s, t;
input.read(s), input.read(t);
SuffixAutomaton automaton(s);
auto match = automaton.longest_common_substring(t);
output.write(match.text_pos), output.write(' ');
output.write(match.text_pos + match.length), output.write(' ');
output.write(match.query_pos), output.write(' ');
output.println(match.query_pos + match.length);
}