#define SKIP_RUNTIME_CHECKS // Verify: https://yukicoder.me/problems/no/430 // Submission: https://yukicoder.me/submissions/1202989 // Library: String/RollingHash.cpp // SPDX-License-Identifier: CC0-1.0 AND LicenseRef-SplitMix64-Public-Domain // SplitMix64の最終混合: https://prng.di.unimi.it/splitmix64.c(LICENSES/LicenseRef-SplitMix64-Public-Domain.txt) // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/rolling_hash.md // // API一覧 // [RollingHash] // RollingHash(s, base): 符号なしバイト列をO(|s|+1)時間・空間で構築。base<2は10、base>modulus-2はmodulus-10に補正。 // RollingHash(values,base[,encode]): vectorの各要素を整数に写して構築。既定では要素自身を使う。 // 64ビット以下の整数の全域に対応。charは符号なしバイト。[-symbol_limit,symbol_limit)の外は混合してから法に写す。symbol_limit=2^59。 // modulus: ハッシュの法2^61-1。ハッシュ値は常に[0,modulus)。 // get(l,r): 半開区間[l,r)のハッシュ、whole(): 全体のハッシュをO(1)で返す。空区間は0。 // size(), empty(), base(): 長さ・空判定・補正後の底をO(1)で返す。 // concat(left,right,right_length): 同じ底の正規化済みハッシュを連結してO(1)で返す。right_length<=size()。 // equal(l,r,other,ol,orr): 同じ底の2区間の長さとハッシュをO(1)で比較する。 // lcp(l,other,ol,limit): 同じ底の接尾辞の最長共通接頭辞長をlimit以下でO(log(min(残長,limit)+1))で返す。 // compare(l,r,other,ol,orr): 同じ底の2区間を整数(文字列は符号なしバイト)の辞書順で比較。-1/0/1。O(log(短い方の長さ+1))。 // 比較にはハッシュ衝突による誤判定の可能性がある。検査有効時は不正な範囲にout_of_range、底・ハッシュにinvalid_argument。 // assign(s): 現在の底で再構築し容量・利用可能な累乗表を再利用、O(旧長+|s|+1)上界、強い例外保証。clear(): 空へ戻して底・容量を保持、O(旧長+1)上界、noexcept。 // assign(values[,encode]): 底を保ってvectorから再構築。encodeや確保の失敗時は元の状態を保つ。 // AVX2対応x86_64では長さ4096以上の構築を並列化。SIRKIT_DISABLE_SIMDで専用処理とCPU判定を除外。 // 元文字列は保持しない。コピーはO(n+1)で独立、代入は容量を再利用し強い例外保証。ムーブ元は空(自己ムーブ代入は保持)。swapはO(1)。 // SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。 #include #if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && \ defined(__x86_64__) && defined(__SIZEOF_INT128__) && \ !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) #include #include #endif #include #include #include #include #include #include #include #include #include #include #include // SIRKIT_NAMESPACE_OPEN_V1 namespace sirkit { #ifndef SIRKIT_ROLLING_HASH_DEFINED #define SIRKIT_ROLLING_HASH_DEFINED namespace detail { inline void CheckRollingHashCapacity(std::size_t size, std::size_t maximum) { if (size >= maximum / 2) throw std::length_error("RollingHash: capacity overflow"); } } class RollingHash { public: static constexpr std::uint64_t modulus = (std::uint64_t{1} << 61) - 1; static constexpr std::int64_t symbol_limit = std::int64_t{1} << 59; RollingHash(std::string_view s, std::uint64_t base) : base_(normalize_base(base)) { detail::CheckRollingHashCapacity(s.size(), data_.max_size()); data_.resize(s.size() + 1); power_data_.resize(s.size() + 1); const std::size_t offset = s.size() + 1; offset_ = offset; Entry* const prefixes = data_.data(); Entry* const powers = power_data_.data(); powers_ = powers; const std::uint64_t factor = base_; std::uint64_t hash = 0; std::uint64_t power = 1; prefixes[0].value = hash; powers[0].value = power; #if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && \ defined(__x86_64__) && defined(__SIZEOF_INT128__) && \ !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) if (s.size() >= 4096 && can_build_avx2()) { build_blocks_avx2(s, factor, prefixes, powers); return; } #endif #if defined(__GNUC__) && !defined(__clang__) && defined(__x86_64__) && \ (!defined(__SIZEOF_INT128__) || defined(SIRKIT_FORCE_STANDARD_ARITHMETIC)) std::size_t i = 0; for (; s.size() - i >= 4; i += 4) { const auto byte0 = static_cast(s[i + 0]); hash = multiply_add_byte(hash, factor, byte0); power = multiply(power, factor); prefixes[i + 1].value = hash; powers[i + 1].value = power; const auto byte1 = static_cast(s[i + 1]); hash = multiply_add_byte(hash, factor, byte1); power = multiply(power, factor); prefixes[i + 2].value = hash; powers[i + 2].value = power; const auto byte2 = static_cast(s[i + 2]); hash = multiply_add_byte(hash, factor, byte2); power = multiply(power, factor); prefixes[i + 3].value = hash; powers[i + 3].value = power; const auto byte3 = static_cast(s[i + 3]); hash = multiply_add_byte(hash, factor, byte3); power = multiply(power, factor); prefixes[i + 4].value = hash; powers[i + 4].value = power; } for (; i < s.size(); ++i) { const auto byte = static_cast(s[i]); hash = multiply_add_byte(hash, factor, byte); power = multiply(power, factor); prefixes[i + 1].value = hash; powers[i + 1].value = power; } #else for (std::size_t i = 0; i < s.size(); ++i) { const auto byte = static_cast(s[i]); hash = multiply_add_byte(hash, factor, byte); power = multiply(power, factor); prefixes[i + 1].value = hash; powers[i + 1].value = power; } #endif } template requires (std::integral>> && sizeof(std::remove_cvref_t>) <= sizeof(std::uint64_t)) RollingHash(const std::vector &values, std::uint64_t base, Encode encode = {}) : base_(normalize_base(base)) { detail::CheckRollingHashCapacity(values.size(), data_.max_size()); offset_ = values.size() + 1; data_.resize(offset_); power_data_.resize(offset_); powers_ = power_data_.data(); data_[0].value = 0; power_data_[0].value = 1; using Integer = std::remove_cvref_t>; constexpr bool wide = std::numeric_limits::digits >= 59; if constexpr (wide) { symbols_.reserve(values.size()); signed_symbols_ = std::signed_integral; } for (std::size_t i = 0; i < values.size(); ++i) { const Integer value = std::invoke(encode, static_cast(values[i])); if constexpr (wide) { symbols_.push_back(static_cast(value)); } const auto key = encode_symbol(value); data_[i + 1].value = add(multiply(data_[i].value, base_), key); power_data_[i + 1].value = multiply(power_data_[i].value, base_); } } void assign(std::string_view s) { detail::CheckRollingHashCapacity(s.size(), data_.max_size()); const std::size_t count = s.size() + 1; const bool reuse_powers = power_data_.size() >= count; // 両方の確保を先に終え、失敗時も内容と非所有ポインタを保つ。 data_.reserve(count); power_data_.reserve(count); data_.resize(count); power_data_.resize(count); symbols_.clear(); offset_ = count; powers_ = power_data_.data(); Entry* const prefixes = data_.data(); Entry* const powers = power_data_.data(); const std::uint64_t factor = base_; std::uint64_t hash = 0; prefixes[0].value = hash; powers[0].value = 1; #if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && \ defined(__x86_64__) && defined(__SIZEOF_INT128__) && \ !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) if (reuse_powers && s.size() >= 4096 && can_build_avx2()) { build_blocks_avx2(s, factor, prefixes, powers); return; } if (!reuse_powers && s.size() >= 4096 && can_build_avx2()) { build_blocks_avx2(s, factor, prefixes, powers); return; } #endif if (reuse_powers) { #if defined(__GNUC__) && !defined(__clang__) && defined(__x86_64__) && \ (!defined(__SIZEOF_INT128__) || defined(SIRKIT_FORCE_STANDARD_ARITHMETIC)) std::size_t i = 0; for (; s.size() - i >= 4; i += 4) { hash = multiply_add_byte(hash, factor, static_cast(s[i + 0])); prefixes[i + 1].value = hash; hash = multiply_add_byte(hash, factor, static_cast(s[i + 1])); prefixes[i + 2].value = hash; hash = multiply_add_byte(hash, factor, static_cast(s[i + 2])); prefixes[i + 3].value = hash; hash = multiply_add_byte(hash, factor, static_cast(s[i + 3])); prefixes[i + 4].value = hash; } for (; i < s.size(); ++i) { hash = multiply_add_byte(hash, factor, static_cast(s[i])); prefixes[i + 1].value = hash; } #else for (std::size_t i = 0; i < s.size(); ++i) { hash = multiply_add_byte(hash, factor, static_cast(s[i])); prefixes[i + 1].value = hash; } #endif } else { std::uint64_t power = 1; #if defined(__GNUC__) && !defined(__clang__) && defined(__x86_64__) && \ (!defined(__SIZEOF_INT128__) || defined(SIRKIT_FORCE_STANDARD_ARITHMETIC)) std::size_t i = 0; for (; s.size() - i >= 4; i += 4) { hash = multiply_add_byte(hash, factor, static_cast(s[i + 0])); power = multiply(power, factor); prefixes[i + 1].value = hash; powers[i + 1].value = power; hash = multiply_add_byte(hash, factor, static_cast(s[i + 1])); power = multiply(power, factor); prefixes[i + 2].value = hash; powers[i + 2].value = power; hash = multiply_add_byte(hash, factor, static_cast(s[i + 2])); power = multiply(power, factor); prefixes[i + 3].value = hash; powers[i + 3].value = power; hash = multiply_add_byte(hash, factor, static_cast(s[i + 3])); power = multiply(power, factor); prefixes[i + 4].value = hash; powers[i + 4].value = power; } for (; i < s.size(); ++i) { hash = multiply_add_byte(hash, factor, static_cast(s[i])); power = multiply(power, factor); prefixes[i + 1].value = hash; powers[i + 1].value = power; } #else for (std::size_t i = 0; i < s.size(); ++i) { hash = multiply_add_byte(hash, factor, static_cast(s[i])); power = multiply(power, factor); prefixes[i + 1].value = hash; powers[i + 1].value = power; } #endif } } void clear() noexcept { data_.clear(); power_data_.clear(); symbols_.clear(); offset_ = 0; powers_ = nullptr; } template requires (std::integral>> && sizeof(std::remove_cvref_t>) <= sizeof(std::uint64_t)) void assign(const std::vector &values, Encode encode = {}) { RollingHash replacement(values, base_, std::move(encode)); swap(replacement); } RollingHash(const RollingHash& other) : data_(other.data_), power_data_(other.power_data_), symbols_(other.symbols_), signed_symbols_(other.signed_symbols_), base_(other.base_), offset_(other.offset_), powers_(data_.empty() ? nullptr : power_data_.data()) {} RollingHash& operator=(const RollingHash& other) { if (this != &other) { symbols_.reserve(other.symbols_.size()); data_.reserve(other.data_.size()); power_data_.reserve(other.power_data_.size()); data_.resize(other.data_.size()); power_data_.resize(other.power_data_.size()); symbols_.resize(other.symbols_.size()); // Entryはtrivially copyable。独立した配列間で、構築済み要素の表現を写す。 if (!other.data_.empty()) { std::memcpy(data_.data(), other.data_.data(), other.data_.size() * sizeof(Entry)); std::memcpy(power_data_.data(), other.power_data_.data(), other.power_data_.size() * sizeof(Entry)); } std::copy(other.symbols_.begin(), other.symbols_.end(), symbols_.begin()); signed_symbols_ = other.signed_symbols_; base_ = other.base_; offset_ = other.offset_; powers_ = data_.empty() ? nullptr : power_data_.data(); } return *this; } RollingHash(RollingHash&& other) noexcept : data_(std::move(other.data_)), power_data_(std::move(other.power_data_)), symbols_(std::move(other.symbols_)), signed_symbols_(other.signed_symbols_), base_(other.base_), offset_(other.offset_), powers_(other.powers_) { other.data_.clear(); other.power_data_.clear(); other.symbols_.clear(); other.offset_ = 0; other.powers_ = nullptr; } RollingHash& operator=(RollingHash&& other) noexcept { if (this != &other) { data_ = std::move(other.data_); power_data_ = std::move(other.power_data_); symbols_ = std::move(other.symbols_); signed_symbols_ = other.signed_symbols_; base_ = other.base_; offset_ = other.offset_; powers_ = other.powers_; other.data_.clear(); other.power_data_.clear(); other.symbols_.clear(); other.offset_ = 0; other.powers_ = nullptr; } return *this; } void swap(RollingHash& other) noexcept { data_.swap(other.data_); power_data_.swap(other.power_data_); symbols_.swap(other.symbols_); std::swap(signed_symbols_, other.signed_symbols_); std::swap(base_, other.base_); std::swap(offset_, other.offset_); std::swap(powers_, other.powers_); } friend void swap(RollingHash& left, RollingHash& right) noexcept { left.swap(right); } [[nodiscard]] std::size_t size() const noexcept { return offset_ == 0 ? 0 : offset_ - 1; } [[nodiscard]] bool empty() const noexcept { return size() == 0; } [[nodiscard]] std::uint64_t base() const noexcept { return base_; } [[nodiscard]] std::uint64_t whole() const noexcept { return offset_ == 0 ? 0 : data_[offset_ - 1].value; } [[nodiscard]] std::uint64_t get(std::size_t l, std::size_t r) const { #ifndef SKIP_RUNTIME_CHECKS check_range(l, r); #endif return get_unchecked(l, r); } [[nodiscard]] std::uint64_t concat(std::uint64_t left, std::uint64_t right, std::size_t right_length) const { #ifndef SKIP_RUNTIME_CHECKS if (right_length > size()) { throw std::out_of_range("RollingHash: concatenation length"); } if (left >= modulus || right >= modulus) { throw std::invalid_argument("RollingHash: noncanonical hash"); } #endif #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) if (right_length == 0) return add(left, right); const __uint128_t product = static_cast<__uint128_t>(left) * powers_[right_length].value + right; const std::uint64_t folded = (static_cast(product) & modulus) + static_cast(product >> 61); return folded >= modulus ? folded - modulus : folded; #else return add(right_length == 0 ? left : multiply(left, powers_[right_length].value), right); #endif } [[nodiscard]] bool equal(std::size_t l, std::size_t r, const RollingHash& other, std::size_t ol, std::size_t orr) const { #ifndef SKIP_RUNTIME_CHECKS check_range(l, r); other.check_range(ol, orr); check_base(other); #endif const std::size_t length = r - l; if (length != orr - ol) return false; if (length == 0) return true; const std::uint64_t start = data_[l].value + modulus - other.data_[ol].value; const std::uint64_t delta = start >= modulus ? start - modulus : start; if (delta == 0) return data_[r].value == other.data_[orr].value; // 開始prefix差の1積だけで2区間のハッシュ差を比較する。 #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) const __uint128_t product = static_cast<__uint128_t>(delta) * powers_[length].value + (other.data_[orr].value + modulus - data_[r].value); return ((static_cast(product) & modulus) + static_cast(product >> 61)) == modulus; #else const std::uint64_t difference = data_[r].value + 5 * modulus - multiply_raw(delta, powers_[length].value) - other.data_[orr].value; return ((difference & modulus) + (difference >> 61)) == modulus; #endif } [[nodiscard]] std::size_t lcp( std::size_t l, const RollingHash& other, std::size_t ol, std::size_t limit = std::numeric_limits::max()) const { #ifndef SKIP_RUNTIME_CHECKS check_range(l, l); other.check_range(ol, ol); check_base(other); #endif return lcp_unchecked(l, other, ol, std::min({size() - l, other.size() - ol, limit})); } [[nodiscard]] int compare(std::size_t l, std::size_t r, const RollingHash& other, std::size_t ol, std::size_t orr) const { #ifndef SKIP_RUNTIME_CHECKS check_range(l, r); other.check_range(ol, orr); check_base(other); #endif const std::size_t length = r - l; const std::size_t other_length = orr - ol; const std::size_t common = lcp_unchecked( l, other, ol, std::min(length, other_length)); if (common == std::min(length, other_length)) { return (length > other_length) - (length < other_length); } if (!symbols_.empty() || !other.symbols_.empty()) { return ordered_symbol(l + common) < other.ordered_symbol(ol + common) ? -1 : 1; } const Entry* const left = data_.data() + l; const Entry* const right = other.data_.data() + ol; const std::uint64_t start = left[0].value + modulus - right[0].value; const std::uint64_t delta = start >= modulus ? start - modulus : start; // lcp_uncheckedが上限未満なら、その次の長さのハッシュは不一致。 // 一致したprefixの次の要素の差は、法の半分以下に収まる。 const std::size_t length_next = common + 1; #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) const __uint128_t product = static_cast<__uint128_t>(delta) * powers_[length_next].value + (right[length_next].value + modulus - left[length_next].value); const std::uint64_t folded = (static_cast(product) & modulus) + static_cast(product >> 61); return static_cast((folded >> 60) & 1U) * 2 - 1; #else const std::uint64_t difference = left[length_next].value + 5 * modulus - multiply_raw(delta, powers_[length_next].value) - right[length_next].value; const std::uint64_t folded = (difference & modulus) + (difference >> 61); return 1 - static_cast((folded >> 60) & 1U) * 2; #endif } private: template std::uint64_t encode_symbol(Integer value) const noexcept { if constexpr (std::same_as) { return static_cast(value); } else { constexpr auto limit = static_cast(symbol_limit); const auto bits = static_cast(value); if constexpr (std::signed_integral) { if (value < -symbol_limit) { return limit + (mix_wide_symbol(bits) & (limit - 1)); } if (value < 0) { return modulus + bits; } } if (bits >= limit) { // 符号が異なる値と従来の狭い整数範囲に、別の剰余を割り当てる。 return 2 * limit + mix_wide_symbol(bits) % (limit - 1); } return bits; } } std::uint64_t mix_wide_symbol(std::uint64_t bits) const noexcept { bits += base_; bits = (bits ^ (bits >> 30)) * 0xbf58476d1ce4e5b9ULL; bits = (bits ^ (bits >> 27)) * 0x94d049bb133111ebULL; return bits ^ (bits >> 31); } std::pair ordered_symbol(std::size_t index) const noexcept { if (!symbols_.empty()) { const auto bits = symbols_[index]; const bool nonnegative = !signed_symbols_ || (bits >> 63) == 0; return {nonnegative, bits}; } const auto residue = get_unchecked(index, index + 1); if (residue > modulus / 2) { return {false, residue - modulus}; } return {true, residue}; } struct Entry { std::uint64_t value; // 構築ループで全要素を設定し、不要なゼロ初期化を避ける。 Entry() noexcept {} }; #if !defined(SIRKIT_DISABLE_SIMD) && (defined(__GNUC__) || defined(__clang__)) && \ defined(__x86_64__) && defined(__SIZEOF_INT128__) && \ !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) template [[gnu::target("avx2"), gnu::noinline]] static void build_blocks_avx2(std::string_view s, std::uint64_t base, Entry* prefixes, Entry* powers) noexcept { static_assert(sizeof(Entry) == sizeof(std::uint64_t)); const auto b2 = multiply(base, base); const auto b3 = multiply(b2, base); const auto b4 = multiply(b2, b2); std::array t1,t2,t3; t1[0] = t2[0] = t3[0] = 0; for (std::size_t c = 1; c < 256; ++c) { t1[c] = add(t1[c - 1], base); t2[c] = add(t2[c - 1], b2); t3[c] = add(t3[c - 1], b3); } // laneは各4文字ブロック内の1〜4文字目に対応する。 const auto factors = _mm256_set_epi64x(b4, b3, b2, base); const auto factors_hi = _mm256_srli_epi64(factors, 32); const auto mask61 = _mm256_set1_epi64x(modulus); const auto mask29 = _mm256_set1_epi64x((std::uint64_t{1} << 29) - 1); const auto threshold = _mm256_set1_epi64x(modulus - 1); auto hs = _mm256_setzero_si256(); [[maybe_unused]] auto ps = _mm256_set1_epi64x(1); auto hr = hs; [[maybe_unused]] auto pr = ps; std::size_t i = 0; for (; s.size() - i >= 4; i += 4) { const auto c0 = static_cast(s[i]); const auto c1 = static_cast(s[i+1]); const auto c2 = static_cast(s[i+2]); const auto c3 = static_cast(s[i+3]); const auto u2 = t1[c0] + c1; const auto u3 = (t2[c0] + t1[c1]) + c2; const auto u4 = (t3[c0] + t2[c1]) + (t1[c2] + c3); const auto ht = _mm256_set_epi64x(u4,u3,u2,c0); const auto hhi = _mm256_srli_epi64(hs,32); const auto hlow = _mm256_mul_epu32(hs,factors); const auto hcross = _mm256_add_epi64(_mm256_mul_epu32(hs,factors_hi),_mm256_mul_epu32(hhi,factors)); const auto hhigh = _mm256_mul_epu32(hhi,factors_hi); auto hsum = _mm256_add_epi64(_mm256_and_si256(hlow,mask61),_mm256_srli_epi64(hlow,61)); hsum = _mm256_add_epi64(hsum,_mm256_slli_epi64(_mm256_and_si256(hcross,mask29),32)); hsum = _mm256_add_epi64(hsum,_mm256_srli_epi64(hcross,29)); hsum = _mm256_add_epi64(hsum,_mm256_slli_epi64(hhigh,3)); hsum = _mm256_add_epi64(hsum,ht); // 文字項を含む和は7p未満。次状態は[0,p+6]で閉じる。 const auto hfold = _mm256_add_epi64(_mm256_and_si256(hsum,mask61),_mm256_srli_epi64(hsum,61)); hs = _mm256_permute4x64_epi64(hfold,_MM_SHUFFLE(3,3,3,3)); hr = _mm256_sub_epi64(hfold,_mm256_and_si256(_mm256_cmpgt_epi64(hfold,threshold),mask61)); if constexpr (ComputePower) { const auto phi = _mm256_srli_epi64(ps,32); const auto plow = _mm256_mul_epu32(ps,factors); const auto pcross = _mm256_add_epi64(_mm256_mul_epu32(ps,factors_hi),_mm256_mul_epu32(phi,factors)); const auto phigh = _mm256_mul_epu32(phi,factors_hi); auto psum = _mm256_add_epi64(_mm256_and_si256(plow,mask61),_mm256_srli_epi64(plow,61)); psum = _mm256_add_epi64(psum,_mm256_slli_epi64(_mm256_and_si256(pcross,mask29),32)); psum = _mm256_add_epi64(psum,_mm256_srli_epi64(pcross,29)); psum = _mm256_add_epi64(psum,_mm256_slli_epi64(phigh,3)); const auto pfold = _mm256_add_epi64(_mm256_and_si256(psum,mask61),_mm256_srli_epi64(psum,61)); ps = _mm256_permute4x64_epi64(pfold,_MM_SHUFFLE(3,3,3,3)); pr = _mm256_sub_epi64(pfold,_mm256_and_si256(_mm256_cmpgt_epi64(pfold,threshold),mask61)); } _mm256_storeu_si256(reinterpret_cast<__m256i*>(prefixes+i+1),hr); if constexpr (ComputePower) _mm256_storeu_si256(reinterpret_cast<__m256i*>(powers+i+1),pr); } auto hash = static_cast(_mm256_extract_epi64(hr,3)); [[maybe_unused]] std::uint64_t power = 1; if constexpr (ComputePower) power = static_cast(_mm256_extract_epi64(pr,3)); for (; i(s[i])); if constexpr (ComputePower) power=multiply(power,base); prefixes[i+1].value=hash; if constexpr (ComputePower) powers[i+1].value=power; } } static bool can_build_avx2() noexcept { static const bool supported = __builtin_cpu_supports("avx2"); return supported; } #endif std::vector data_, power_data_; std::vector symbols_; bool signed_symbols_ = false; std::uint64_t base_; std::size_t offset_ = 0; const Entry* powers_ = nullptr; // power_data_の累乗領域への非所有ポインタ。 static constexpr std::uint64_t normalize_base(std::uint64_t base) noexcept { return base < 2 ? 10 : (base > modulus - 2 ? modulus - 10 : base); } static constexpr std::uint64_t add(std::uint64_t a, std::uint64_t b) noexcept { const std::uint64_t sum = a + b; return sum >= modulus ? sum - modulus : sum; } static constexpr std::uint64_t multiply_raw(std::uint64_t a, std::uint64_t b) noexcept { #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && \ !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) const __uint128_t product = static_cast<__uint128_t>(a) * b; const std::uint64_t folded = (static_cast(product) & modulus) + static_cast(product >> 61); #else // 32bitの4積を2^61=1、2^64=8として直接折り返す。 const std::uint64_t a0 = static_cast(a); const std::uint64_t b0 = static_cast(b); const std::uint64_t a1 = a >> 32; const std::uint64_t b1 = b >> 32; const std::uint64_t low = a0 * b0; const std::uint64_t cross = a0 * b1 + a1 * b0; constexpr std::uint64_t mask29 = (std::uint64_t{1} << 29) - 1; const std::uint64_t sum = (low & modulus) + (low >> 61) + ((cross & mask29) << 32) + (cross >> 29) + ((a1 * b1) << 3); const std::uint64_t folded = sum; #endif return folded; } static constexpr std::uint64_t multiply(std::uint64_t a, std::uint64_t b) noexcept { std::uint64_t folded = multiply_raw(a, b); #if !((defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__)) || defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) folded = (folded & modulus) + (folded >> 61); #endif return folded >= modulus ? folded - modulus : folded; } // byteは0..255。乗算結果への加算を正規化前にまとめる。 static constexpr std::uint64_t multiply_add_byte( std::uint64_t a, std::uint64_t b, unsigned char byte) noexcept { #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) const __uint128_t product = static_cast<__uint128_t>(a) * b + byte; const std::uint64_t folded = (static_cast(product) & modulus) + static_cast(product >> 61); #else const std::uint64_t sum = multiply_raw(a, b) + byte; const std::uint64_t folded = (sum & modulus) + (sum >> 61); #endif return folded >= modulus ? folded - modulus : folded; } [[nodiscard]] std::uint64_t get_unchecked(std::size_t l, std::size_t r) const noexcept { if (l == r) { return 0; } const std::uint64_t right = data_[r].value; const std::uint64_t left = multiply_raw(data_[l].value, powers_[r - l].value); #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) const std::uint64_t difference = right + 2 * modulus - left; #else // raw積は4p未満、右辺全体は5p未満で64bitに収まる。 const std::uint64_t difference = right + 4 * modulus - left; #endif const std::uint64_t folded = (difference & modulus) + (difference >> 61); return folded >= modulus ? folded - modulus : folded; } [[nodiscard]] std::size_t lcp_unchecked(std::size_t l, const RollingHash& other, std::size_t ol, std::size_t limit) const noexcept { if (limit == 0) return 0; const Entry* const left = data_.data() + l; const Entry* const right = other.data_.data() + ol; const Entry* const powers = powers_; const std::uint64_t start = left[0].value + modulus - right[0].value; const std::uint64_t delta = start >= modulus ? start - modulus : start; // 開始接頭辞が同じなら、端点の比較だけで区間ハッシュを比較できる。 if (delta == 0) { if (left[limit].value == right[limit].value) return limit; std::size_t low = 0, high = limit - 1; while (low < high) { const std::size_t middle = high - (high - low) / 2; if (left[middle].value == right[middle].value) low = middle; else high = middle - 1; } return low; } const auto equal_prefix = [&](std::size_t length) noexcept { #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) // 0(delta) * powers[length].value + (right[length].value + modulus - left[length].value); return ((static_cast(product) & modulus) + static_cast(product >> 61)) == modulus; #else // raw積は4p未満。0> 61)) == modulus; #endif }; if (!equal_prefix(1)) return 0; if (equal_prefix(limit)) return limit; // 長さ1だけ一致する照会は、広い範囲を二分探索しない。 if (!equal_prefix(2)) return 1; std::size_t low = 2, high = limit - 1; while (low < high) { const std::size_t middle = high - (high - low) / 2; if (equal_prefix(middle)) low = middle; else high = middle - 1; } return low; } #ifndef SKIP_RUNTIME_CHECKS void check_range(std::size_t l, std::size_t r) const { if (l > r || r > size()) { throw std::out_of_range("RollingHash: substring range"); } } void check_base(const RollingHash& other) const { if (base_ != other.base_) { throw std::invalid_argument("RollingHash: different bases"); } } #endif }; #endif } // namespace sirkit // SIRKIT_NAMESPACE_CLOSE_V1 // SIRKIT_NAMESPACE_END_V1 namespace sirkit {} using namespace sirkit; // SPDX-License-Identifier: CC0-1.0 // Verify I/O: Verify/current/common/fast_io.hpp // SPDX-License-Identifier: CC0-1.0 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef SIRKIT_VERIFY_FAST_IO_DEFINED #define SIRKIT_VERIFY_FAST_IO_DEFINED // VerifyInput(file=stdin): 非所有のFILEから読む。別の入力方式と混用しない。 // >> 整数: 64bit以下の十進整数を読む。検査省略時は値域内の正しい入力を前提とする。 // >> char/string: 空白を飛ばし、1文字/空白までの文字列を読む。 // >> 浮動小数点: 十進文字列を変換する。通常のCロケールで使う。 // bool / !: 直前までの読み取りが成功しているか/失敗したかを返す。 class VerifyInput { static constexpr std::size_t buffer_size = 1 << 17; std::FILE* file_; std::array buffer_; std::size_t position_ = 0, size_ = 0; bool good_ = true; int peek() { if (position_ == size_) { size_ = std::fread(buffer_.data(), 1, buffer_size, file_); buffer_[size_] = 0; // 補充後の末尾は常に数字でない番兵。 position_ = 0; if (size_ == 0) return EOF; } return buffer_[position_]; } int skip_space() { int c; while ((c = peek()) != EOF && c <= ' ') ++position_; if (c == EOF) good_ = false; return c; } public: explicit VerifyInput(std::FILE* file = stdin) : file_(file) {} VerifyInput(const VerifyInput&) = delete; VerifyInput& operator=(const VerifyInput&) = delete; explicit operator bool() const noexcept { return good_; } bool operator!() const noexcept { return !good_; } template requires (std::is_integral_v && sizeof(T) <= sizeof(std::uint64_t) && !std::is_same_v) VerifyInput& operator>>(T& result) { if (!good_) return *this; int c = skip_space(); if (c == EOF) return *this; bool negative = false; if (c == '-' || c == '+') { negative = c == '-'; ++position_; c = peek(); } if (c == EOF) { good_ = false; return *this; } #ifndef SKIP_RUNTIME_CHECKS if (c < '0' || c > '9') { good_ = false; return *this; } // 先頭の0を除けば、20桁以下の末尾直前の値はuint64_tに収まる。 while (c == '0') { ++position_; c = peek(); } std::uint64_t previous = 0; unsigned last_digit = 0; std::size_t digits = 0; #endif std::uint64_t value = 0; #ifdef SKIP_RUNTIME_CHECKS // バッファ末尾の番兵で内側の範囲判定を省き、数字が境界をまたぐときだけ補充する。 for (;;) { const unsigned char* first = buffer_.data() + position_; const unsigned char* cursor = first; while (static_cast(*cursor - '0') < 10) { value = value * 10 + static_cast(*cursor - '0'); ++cursor; } position_ += static_cast(cursor - first); if (position_ != size_) break; c = peek(); if (c == EOF) break; } #else while (c >= '0' && c <= '9') { previous = value; last_digit = static_cast(c - '0'); if (digits <= 20) ++digits; value = value * 10 + static_cast(c - '0'); ++position_; c = peek(); } #endif #ifndef SKIP_RUNTIME_CHECKS constexpr auto maximum = std::numeric_limits::max(); if ((c != EOF && c > ' ') || digits > 20 || (digits == 20 && (previous > maximum / 10 || (previous == maximum / 10 && last_digit > maximum % 10)))) { good_ = false; return *this; } std::uint64_t limit = static_cast(std::numeric_limits::max()); if constexpr (std::is_signed_v) limit += negative; else if (negative && value != 0) good_ = false; if (value > limit) good_ = false; if (!good_) return *this; #endif if constexpr (std::is_signed_v) { constexpr std::uint64_t minimum_magnitude = static_cast(std::numeric_limits::max()) + 1; // -(最小値)は評価せず、絶対値が最大値+1のときだけ最小値を使う。 result = negative ? (value == minimum_magnitude ? std::numeric_limits::min() : static_cast(-static_cast(value))) : static_cast(value); } else result = static_cast(value); return *this; } VerifyInput& operator>>(char& result) { if (!good_) return *this; const int c = skip_space(); if (c != EOF) { result = static_cast(c); ++position_; } return *this; } VerifyInput& operator>>(std::string& result) { if (!good_) return *this; int c = skip_space(); if (c == EOF) return *this; result.clear(); for (;;) { const std::size_t first = position_; while (position_ < size_ && buffer_[position_] > ' ') ++position_; result.append(reinterpret_cast(buffer_.data() + first), position_ - first); if (position_ != size_ || peek() == EOF) break; } return *this; } template requires std::is_floating_point_v VerifyInput& operator>>(T& result) { std::string token; *this >> token; if (!good_) return *this; #ifndef SKIP_RUNTIME_CHECKS char* end = nullptr; const long double value = std::strtold(token.c_str(), &end); if (end != token.c_str() + token.size()) good_ = false; else result = static_cast(value); #else result = static_cast(std::strtold(token.c_str(), nullptr)); #endif return *this; } }; // VerifyOutput(file=stdout): 非所有のFILEへ書く。破棄時にflushし、FILEは閉じない。 // << 整数/char/文字列/浮動小数点: 値を出力する。整数は64bit以下に対応する。 // fixed(digits): 浮動小数点を小数点以下digits桁で出力する(digits>=0)。 // flush(): バッファの内容をFILEへ渡す。bool / !で書き込み失敗を確認できる。 class VerifyOutput { static constexpr std::size_t buffer_size = 1 << 17; std::FILE* file_; std::array buffer_; std::size_t size_ = 0; int precision_ = 6; bool fixed_ = false, good_ = true; void write(std::string_view text) { while (!text.empty() && good_) { if (size_ == buffer_.size()) flush(); const auto count = std::min(text.size(), buffer_.size() - size_); std::memcpy(buffer_.data() + size_, text.data(), count); size_ += count; text.remove_prefix(count); } } public: explicit VerifyOutput(std::FILE* file = stdout) : file_(file) {} VerifyOutput(const VerifyOutput&) = delete; VerifyOutput& operator=(const VerifyOutput&) = delete; ~VerifyOutput() { flush(); } explicit operator bool() const noexcept { return good_; } bool operator!() const noexcept { return !good_; } VerifyOutput& fixed(int digits) { if (digits < 0) throw std::invalid_argument("negative output precision"); fixed_ = true; precision_ = digits; return *this; } void flush() noexcept { std::size_t written = 0; while (written < size_ && good_) { const auto count = std::fwrite(buffer_.data() + written, 1, size_ - written, file_); if (count == 0) good_ = false; written += count; } size_ = 0; } template requires (std::is_integral_v && sizeof(T) <= sizeof(std::uint64_t) && !std::is_same_v) VerifyOutput& operator<<(T value) { if constexpr (std::is_same_v) return *this << static_cast('0' + value); else { constexpr std::size_t capacity = std::numeric_limits::digits10 + 3; if (buffer_.size() - size_ < capacity) flush(); if (!good_) return *this; const auto end = std::to_chars(buffer_.data() + size_, buffer_.data() + size_ + capacity, value).ptr; size_ = static_cast(end - buffer_.data()); return *this; } } VerifyOutput& operator<<(char value) { if (size_ == buffer_.size()) flush(); if (good_) buffer_[size_++] = value; return *this; } VerifyOutput& operator<<(std::string_view value) { write(value); return *this; } VerifyOutput& operator<<(const std::string& value) { write(value); return *this; } VerifyOutput& operator<<(const char* value) { write(value); return *this; } template requires std::is_floating_point_v VerifyOutput& operator<<(T value) { char local[128]; const char* format = fixed_ ? "%.*Lf" : "%.*Lg"; const int count = std::snprintf(local, sizeof(local), format, precision_, static_cast(value)); if (count < 0) good_ = false; else if (static_cast(count) < sizeof(local)) write(std::string_view(local, static_cast(count))); else { std::vector text(static_cast(count) + 1); std::snprintf(text.data(), text.size(), format, precision_, static_cast(value)); write(std::string_view(text.data(), static_cast(count))); } return *this; } }; inline VerifyInput verify_in; inline VerifyOutput verify_out; #endif #include #include #include #include #include // 大文字・長さ10以下の同じ長さの語なら、底27のハッシュは衝突しない。 // 26文字の差は25以下で、各窓の多項式値も2^61-1より小さい。 int main() { std::string text; int count{}; verify_in >> text >> count; const RollingHash text_hash(text, 27); std::array, 11> patterns; while (count--) { std::string word; verify_in >> word; const RollingHash pattern_hash(word, 27); patterns[word.size()].insert(pattern_hash.whole()); } std::uint64_t answer = 0; for (std::size_t length = 1; length <= 10 && length <= text.size(); ++length) { if (patterns[length].empty()) continue; for (std::size_t i = 0; i <= text.size() - length; ++i) answer += patterns[length].contains(text_hash.get(i, i + length)); } verify_out << answer << '\n'; }