shogo-library

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

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/aoj/alds1/alds1-14-b.1.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_14_B"

#include <iostream>
#include <string>

#include "../../../src/string/rolling-hash.hpp"

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::string t, p;
    std::cin >> t >> p;
    RollingHash rh;
    auto ht = rh.build(t);
    auto hp = rh.build(p);
    int n = t.size(), m = p.size();
    unsigned long long target = rh.query(hp, 0, m);
    for (int i = 0; i + m <= n; i++) {
        if (rh.query(ht, i, i + m) == target) std::cout << i << '\n';
    }
}
#line 1 "test/aoj/alds1/alds1-14-b.1.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_14_B"

#include <iostream>
#include <string>

#line 2 "src/string/rolling-hash.hpp"

/**
 * @file rolling-hash.hpp
 * @brief ローリングハッシュ
 */

#include <cassert>
#include <iterator>
#include <random>
#line 12 "src/string/rolling-hash.hpp"
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>

#line 2 "src/utility/range.hpp"

/**
 * @file range.hpp
 * @brief Python の range のような整数列と、その直積の Grid
 */

#line 9 "src/utility/range.hpp"
#include <cstddef>
#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 2 "src/utility/traits.hpp"

/**
 * @file traits.hpp
 * @brief 型特性
 */

#line 9 "src/utility/traits.hpp"
#include <functional>
#line 11 "src/utility/traits.hpp"
#include <set>
#line 14 "src/utility/traits.hpp"

#if __cplusplus >= 202002L
#include <concepts>
#include <ranges>
#endif

namespace internal_traits {
using std::begin, std::end;

#if __cplusplus >= 202002L
template <class T>
    struct is_range_impl : std::bool_constant < requires(T& t) {
    begin(t);
    end(t);
}>{};
#else
template <class T, class = void>
struct is_range_impl : std::false_type {};
template <class T>
struct is_range_impl<T, std::void_t<decltype(begin(std::declval<T&>()), end(std::declval<T&>()))>> : std::true_type {};
#endif

// サイズ付き範囲から要素を直接構築するコンストラクタで共有する。
#if __cplusplus >= 202002L
template <class R, class S>
concept sized_constructible_range = std::ranges::input_range<R> && std::ranges::sized_range<R> &&
                                    std::is_constructible_v<S, std::ranges::range_reference_t<R>>;

template <class R>
auto range_size(R& r) {
    return std::ranges::size(r);
}
template <class R>
auto range_begin(R& r) {
    return std::ranges::begin(r);
}
template <class R>
using range_value_t = std::ranges::range_value_t<R>;
#else
using std::size;
template <class R>
auto range_size(R& r) -> decltype(size(r)) {
    return size(r);
}
template <class R>
auto range_begin(R& r) -> decltype(begin(r)) {
    return begin(r);
}
template <class R>
using range_value_t = typename std::iterator_traits<decltype(range_begin(std::declval<R&>()))>::value_type;

template <class R, class S, class = void>
struct is_sized_constructible_range : std::false_type {};
template <class R, class S>
struct is_sized_constructible_range<R, S, std::void_t<decltype(range_size(std::declval<R&>())), decltype(++std::declval<decltype(begin(std::declval<R&>()))&>()), decltype(begin(std::declval<R&>()) != end(std::declval<R&>())), decltype(*begin(std::declval<R&>()))>>
    : std::is_constructible<S, decltype(*begin(std::declval<R&>()))> {};
#endif
}  // namespace internal_traits

template <class T>
struct is_range : internal_traits::is_range_impl<T>::type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;

#if __cplusplus >= 202002L
#define HAS_METHOD(func_name)                                                                   \
    namespace internal_traits {                                                                 \
    template <class T>                                                                          \
    concept has_##func_name##_impl = requires { std::declval<T>().func_name(); };               \
    }                                                                                           \
    template <class T>                                                                          \
    struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T>> {}; \
    template <class T>                                                                          \
    inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;

#define HAS_METHOD_ARG(func_name)                                                                  \
    namespace internal_traits {                                                                    \
    template <class T, class U>                                                                    \
    concept has_##func_name##_impl = requires { std::declval<T>().func_name(std::declval<U>()); }; \
    }                                                                                              \
    template <class T, class U>                                                                    \
    struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T, U>> {}; \
    template <class T, class U>                                                                    \
    inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#else
#define HAS_METHOD(func_name)                                                              \
    namespace internal_traits {                                                            \
    template <class T, class = void>                                                       \
    struct has_##func_name##_impl : std::false_type {};                                    \
    template <class T>                                                                     \
    struct has_##func_name##_impl<T, std::void_t<decltype(std::declval<T>().func_name())>> \
        : std::true_type {};                                                               \
    }                                                                                      \
    template <class T>                                                                     \
    struct has_##func_name : internal_traits::has_##func_name##_impl<T>::type {};          \
    template <class T>                                                                     \
    inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;

#define HAS_METHOD_ARG(func_name)                                                                              \
    namespace internal_traits {                                                                                \
    template <class T, typename U, class = void>                                                               \
    struct has_##func_name##_impl : std::false_type {};                                                        \
    template <class T, typename U>                                                                             \
    struct has_##func_name##_impl<T, U, std::void_t<decltype(std::declval<T>().func_name(std::declval<U>()))>> \
        : std::true_type {};                                                                                   \
    }                                                                                                          \
    template <class T, typename U>                                                                             \
    struct has_##func_name : internal_traits::has_##func_name##_impl<T, U>::type {};                           \
    template <class T, typename U>                                                                             \
    inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#endif

HAS_METHOD(repr)
HAS_METHOD(type_str)
HAS_METHOD(initializer_str)
HAS_METHOD(max)
HAS_METHOD(min)
HAS_METHOD(reversed)
HAS_METHOD(sorted)
HAS_METHOD(sum)
HAS_METHOD(product)
HAS_METHOD(product_xor)
HAS_METHOD_ARG(count)
HAS_METHOD_ARG(find)
HAS_METHOD_ARG(lower_bound)
HAS_METHOD_ARG(upper_bound)

#define ENABLE_IF_T_IMPL(expr) std::enable_if_t<expr, std::nullptr_t> = nullptr
#define ENABLE_IF_T(...) ENABLE_IF_T_IMPL((__VA_ARGS__))

namespace internal_traits {
// 射影 (proj) の既定値
#if __cplusplus >= 202002L
using identity = std::identity;
#else
struct identity {
    using is_transparent = void;
    template <class T>
    constexpr T&& operator()(T&& x) const noexcept {
        return std::forward<T>(x);
    }
};
#endif
}  // namespace internal_traits

template <class C>
using mem_value_type = typename C::value_type;
template <class C>
using mem_difference_type = typename C::difference_type;

namespace internal_traits {
template <class T, class = void>
struct is_sorted_container_impl : std::false_type {};
template <class T>
struct is_sorted_container_impl<std::set<T>> : std::true_type {};
template <class T>
struct is_sorted_container_impl<std::multiset<T>> : std::true_type {};
}  // namespace internal_traits
template <class T>
struct is_sorted_container : internal_traits::is_sorted_container_impl<T>::type {};
template <class T>
inline constexpr bool is_sorted_container_v = is_sorted_container<T>::value;
#line 19 "src/string/rolling-hash.hpp"

class RHString;
class RollingHash2D;

/**
 * @brief ローリングハッシュ
 *
 * ビット演算による高速化のためハッシュはMOD = 2^61-1で計算される
 *
 * 10^8個くらいなら99%の確率で衝突する組が存在しない
 */
class RollingHash {
    constexpr static unsigned long long MASK30 = (1ULL << 30) - 1;
    constexpr static unsigned long long MASK31 = (1ULL << 31) - 1;
    constexpr static unsigned long long MOD = (1ULL << 61) - 1;

    // a < MOD, b < MOD必須
    constexpr static unsigned long long add(unsigned long long a, unsigned long long b) {
        if ((a += b) >= MOD) a -= MOD;
        return a;
    }

    // a < MOD, b < MOD必須
    constexpr static unsigned long long mul(unsigned long long a, unsigned long long b) {
        __uint128_t c = static_cast<__uint128_t>(a) * b;
        return add(static_cast<unsigned long long>(c >> 61), static_cast<unsigned long long>(c & MOD));
    }

    void expand(long long n) {
        while (static_cast<long long>(power.size()) <= n) power.push_back(mul(power.back(), _base));
    }
    // base の逆元の累乗を n 乗まで用意する (RHString の端を削るときだけ使う)
    void expand_inv(long long n) {
        if (inv_power.empty()) {
            // MOD は素数なので base^(MOD - 2) が逆元
            unsigned long long inv = 1, b = _base, e = MOD - 2;
            for (; e > 0; e >>= 1, b = mul(b, b))
                if (e & 1) inv = mul(inv, b);
            inv_base = inv;
            inv_power = {1};
        }
        while (static_cast<long long>(inv_power.size()) <= n) inv_power.push_back(mul(inv_power.back(), inv_base));
    }
    unsigned long long inv_base = 0;
    std::vector<unsigned long long> inv_power;  // base の逆元の累乗

   public:
    /**
     * @brief 要素を[0, MOD)の値に変換する
     * @note charは符号に関わらず0~255として扱う 負の整数はMODで正規化する
     */
    template <typename T>
    constexpr static unsigned long long to_value(const T& x) {
        using U = std::decay_t<T>;
        if constexpr (std::is_same_v<U, char> || std::is_same_v<U, signed char>) {
            return static_cast<unsigned char>(x);
        } else if constexpr (std::is_integral_v<U> && std::is_signed_v<U>) {
            long long v = static_cast<long long>(x) % static_cast<long long>(MOD);
            return v < 0 ? v + MOD : v;
        } else {
            return static_cast<unsigned long long>(x) % MOD;
        }
    }

   private:
    unsigned int _base;
    std::vector<unsigned long long> power;

   public:
    /**
     * @brief ハッシュの基数
     */
    unsigned int base() const { return _base; }

    /**
     * @brief コンストラクタ
     *
     * @param base ハッシュの基数 省略するとランダム
     */
    explicit RollingHash(unsigned int base = 0) : _base(base) {
        if (base == 0) {
            std::mt19937 mt(std::random_device{}());
            _base = std::uniform_int_distribution<unsigned int>(129, ~0U)(mt);
        }
        power = {1};
    }

    /**
     * @brief 配列/文字列のイテレータ間のハッシュの計算(O(N))
     *
     * @tparam It イテレータ
     * @param first 配列の開始イテレータ
     * @param last 配列の終了イテレータ
     * @return std::vector<unsigned long long> 先頭から各要素数分のハッシュ
     */
    template <typename It>
    std::vector<unsigned long long> build(It first, It last) {
        std::vector<unsigned long long> res;
        if constexpr (std::is_convertible_v<typename std::iterator_traits<It>::iterator_category, std::random_access_iterator_tag>) {
            res.reserve(last - first + 1);
        }
        res.push_back(0);
        for (; first != last; ++first) {
            res.push_back(add(mul(res.back(), _base), to_value(*first)));
        }
        return res;
    }

    /**
     * @brief 配列/文字列全体のハッシュの計算(O(N))
     *
     * @param s 配列/文字列
     * @return std::vector<unsigned long long> 先頭から各文字数分のハッシュ
     */
    template <typename R>
    std::vector<unsigned long long> build(R&& s) {
        using std::begin, std::end;
        return build(begin(s), end(s));
    }

    /**
     * @brief [l,r)のハッシュの計算(O(1))
     *
     * @param hash 先頭からのハッシュ
     * @param l 区間の左端
     * @param r 区間の右端
     * @return unsigned long long [l,r)のハッシュ
     */
    unsigned long long query(const std::vector<unsigned long long>& hash, long long l, long long r) {
        assert(0 <= l && l <= r && r < static_cast<long long>(hash.size()));
        expand(r - l);
        return add(hash[r], MOD - mul(hash[l], power[r - l]));
    }

    friend RHString;
    friend RollingHash2D;
};

/**
 * @brief ローリングハッシュによって管理される文字列型
 */
class RHString {
    RollingHash& rh;
    long long sz;              //!< 長さ
    unsigned long long hash1;  //!< 正順
    unsigned long long hash2;  //!< 逆順
   public:
    /** @brief 正順のハッシュ */
    unsigned long long val() const { return hash1; }
    /** @brief 逆順のハッシュ */
    unsigned long long reverse_val() const { return hash2; }
    /**
     * @brief コンストラクタ
     * 予めRollingHashをインスタンス化しておく必要がある
     */
    explicit RHString(RollingHash& rh) : rh(rh), sz(0), hash1(0), hash2(0) {}
    RHString(RollingHash& rh, long long sz, unsigned long long hash1, unsigned long long hash2) : rh(rh), sz(sz), hash1(hash1), hash2(hash2) {}
    RHString(const RHString& o) : rh(o.rh), sz(o.sz), hash1(o.hash1), hash2(o.hash2) {}
    /**
     * @brief vectorなどで初期化する
     */
    template <class R, ENABLE_IF_T(is_range_v<R> && !std::is_convertible_v<R, std::string_view>)>
    RHString(RollingHash& rh, R&& v) : rh(rh) {
        using std::begin, std::end, std::rbegin, std::rend;
        sz = static_cast<long long>(std::distance(begin(v), end(v)));
        hash1 = rh.build(begin(v), end(v)).back();
        hash2 = rh.build(rbegin(v), rend(v)).back();
    }
    /**
     * @brief charやunsigned long longなどで初期化する
     */
    template <class T, ENABLE_IF_T(std::is_convertible_v<T, unsigned long long> && !std::is_convertible_v<T, std::string_view>)>
    RHString(RollingHash& rh, T&& x) : rh(rh) {
        sz = 1;
        hash1 = RollingHash::to_value(x);
        hash2 = hash1;
    }
    /**
     * @brief 文字列(string, const char*, string_view)で初期化する
     */
    RHString(RollingHash& rh, std::string_view s) : rh(rh) {
        sz = static_cast<long long>(s.size());
        hash1 = rh.build(s.begin(), s.end()).back();
        hash2 = rh.build(s.rbegin(), s.rend()).back();
    }

    /**
     * @brief 回文か否か
     */
    bool is_palindrome() const {
        return hash1 == hash2;
    }
    long long size() const {
        return sz;
    }
    void clear() {
        sz = 0;
        hash1 = 0;
        hash2 = 0;
    }
    bool empty() const {
        return sz == 0;
    }
    /**
     * @brief 先頭の t を取り除く (先頭が t であること。ハッシュからは確かめられないので、違うと値が壊れる) O(1) (累乗の表を伸ばす分を除く)
     * t は RHString のほか、RHString を作れるもの (文字・文字列など) でもよい
     */
    void remove_prefix(const RHString& t) {
        assert(&rh == &t.rh && t.sz <= sz);
        // s = t + u から u: hash1(u) = hash1(s) - hash1(t) B^|u|、hash2(u) = (hash2(s) - hash2(t)) B^-|t|
        const long long u = sz - t.sz;
        rh.expand(u);
        rh.expand_inv(t.sz);
        hash1 = rh.add(hash1, RollingHash::MOD - rh.mul(t.hash1, rh.power[u]));
        hash2 = rh.mul(rh.add(hash2, RollingHash::MOD - t.hash2), rh.inv_power[t.sz]);
        sz = u;
    }
    /**
     * @brief 末尾の t を取り除く (末尾が t であること。ハッシュからは確かめられないので、違うと値が壊れる) O(1) (累乗の表を伸ばす分を除く)
     * t は RHString のほか、RHString を作れるもの (文字・文字列など) でもよい
     */
    void remove_suffix(const RHString& t) {
        assert(&rh == &t.rh && t.sz <= sz);
        // s = u + t から u: hash1(u) = (hash1(s) - hash1(t)) B^-|t|、hash2(u) = hash2(s) - hash2(t) B^|u|
        const long long u = sz - t.sz;
        rh.expand(u);
        rh.expand_inv(t.sz);
        hash1 = rh.mul(rh.add(hash1, RollingHash::MOD - t.hash1), rh.inv_power[t.sz]);
        hash2 = rh.add(hash2, RollingHash::MOD - rh.mul(t.hash2, rh.power[u]));
        sz = u;
    }
    template <class T, ENABLE_IF_T(!std::is_same_v<std::decay_t<T>, RHString>)>
    void remove_prefix(T&& x) {
        remove_prefix(RHString(rh, std::forward<T>(x)));
    }
    template <class T, ENABLE_IF_T(!std::is_same_v<std::decay_t<T>, RHString>)>
    void remove_suffix(T&& x) {
        remove_suffix(RHString(rh, std::forward<T>(x)));
    }
    RHString& operator+=(const RHString& o) {
        assert(&rh == &o.rh);
        rh.expand(sz);
        rh.expand(o.sz);
        hash1 = rh.add(rh.mul(hash1, rh.power[o.sz]), o.hash1);
        hash2 = rh.add(hash2, rh.mul(o.hash2, rh.power[sz]));
        sz += o.sz;
        return *this;
    }
    /**
     * @brief 再代入する
     * RollingHashは同じものである必要がある
     */
    void assign(const RHString& o) {
        assert(&rh == &o.rh);
        sz = o.sz;
        hash1 = o.hash1;
        hash2 = o.hash2;
    }
    /**
     * @brief vectorなどを再代入する
     */
    template <class R, ENABLE_IF_T(is_range_v<R> && !std::is_convertible_v<R, std::string_view>)>
    void assign(R&& v) {
        using std::begin, std::end, std::rbegin, std::rend;
        sz = static_cast<long long>(std::distance(begin(v), end(v)));
        hash1 = rh.build(begin(v), end(v)).back();
        hash2 = rh.build(rbegin(v), rend(v)).back();
    }
    /**
     * @brief charやunsigned long longなどを再代入する
     */
    template <class T, ENABLE_IF_T(std::is_convertible_v<T, unsigned long long> && !std::is_convertible_v<T, std::string_view>)>
    void assign(T&& x) {
        sz = 1;
        hash1 = RollingHash::to_value(x);
        hash2 = hash1;
    }
    /**
     * @brief 文字列(string, const char*, string_view)を再代入する
     */
    void assign(std::string_view s) {
        sz = static_cast<long long>(s.size());
        hash1 = rh.build(s.begin(), s.end()).back();
        hash2 = rh.build(s.rbegin(), s.rend()).back();
    }
    /**
     * @brief 再代入する
     * RollingHashは同じものである必要がある
     */
    RHString& operator=(const RHString& o) {
        assign(o);
        return *this;
    }
    /**
     * @brief vectorなどを再代入する
     */
    template <class R, ENABLE_IF_T(is_range_v<R> && !std::is_convertible_v<R, std::string_view>)>
    RHString& operator=(R&& v) {
        assign(v);
        return *this;
    }
    /**
     * @brief charやunsigned long longなどを再代入する
     */
    template <class T, ENABLE_IF_T(std::is_convertible_v<T, unsigned long long> && !std::is_convertible_v<T, std::string_view>)>
    RHString& operator=(T&& x) {
        assign(x);
        return *this;
    }
    /**
     * @brief 文字列(string, const char*, string_view)を再代入する
     */
    RHString& operator=(std::string_view s) {
        assign(s);
        return *this;
    }
    friend RHString operator+(const RHString& t1, const RHString& t2) {
        RHString ret = t1;
        ret += t2;
        return ret;
    }
    friend bool operator==(const RHString& t1, const RHString& t2) {
        assert(&t1.rh == &t2.rh);
        return t1.sz == t2.sz && t1.hash1 == t2.hash1 && t1.hash2 == t2.hash2;
    }
    friend bool operator!=(const RHString& t1, const RHString& t2) { return !(t1 == t2); }
};

/**
 * @brief 2 次元のローリングハッシュ
 *
 * 行方向と列方向で別の基数を使い、表の左上からの累積ハッシュで長方形のハッシュを O(1) で求める
 * H[i][j] = Σ_{a < i, b < j} v[a][b] base1^(i-1-a) base2^(j-1-b)
 */
class RollingHash2D {
    using ull = unsigned long long;
    RollingHash rh1, rh2;  // 行方向 (上下) と列方向 (左右)

    static ull add(ull a, ull b) { return RollingHash::add(a, b); }
    static ull sub(ull a, ull b) { return RollingHash::add(a, RollingHash::MOD - b); }
    static ull mul(ull a, ull b) { return RollingHash::mul(a, b); }

   public:
    /**
     * @brief コンストラクタ
     *
     * @param base1 行方向の基数 省略するとランダム
     * @param base2 列方向の基数 省略するとランダム
     */
    explicit RollingHash2D(unsigned int base1 = 0, unsigned int base2 = 0) : rh1(base1), rh2(base2) {}

    /**
     * @brief 表 (std::vector<std::string> や std::vector<std::vector<T>>) の累積ハッシュ O(HW)
     *
     * @return std::vector<std::vector<unsigned long long>> (H + 1) 行 (W + 1) 列の表。[i][j] は左上 i 行 j 列のハッシュ
     */
    template <typename Grid>
    std::vector<std::vector<ull>> build(const Grid& grid) {
        using std::size;
        const long long h = size(grid), w = h == 0 ? 0 : size(grid[0]);
        std::vector<std::vector<ull>> res(h + 1, std::vector<ull>(w + 1, 0));
        const ull b1 = rh1.base(), b2 = rh2.base(), b12 = mul(b1, b2);
        for (long long i = 0; i < h; i++) {
            assert(static_cast<long long>(size(grid[i])) == w);
            for (long long j = 0; j < w; j++) {
                ull v = add(mul(res[i][j + 1], b1), mul(res[i + 1][j], b2));
                res[i + 1][j + 1] = add(sub(v, mul(res[i][j], b12)), RollingHash::to_value(grid[i][j]));
            }
        }
        return res;
    }

    /**
     * @brief region のハッシュ O(1) (初回は長さ分)。行・列の step は 1
     */
    ull query(const std::vector<std::vector<ull>>& hash, const Grid& region) {
        assert(region.rows.step == 1 && region.cols.step == 1);
        const long long i1 = region.rows.start, i2 = region.rows.stop;
        const long long j1 = region.cols.start, j2 = region.cols.stop;
        assert(0 <= i1 && i1 <= i2 && i2 < static_cast<long long>(hash.size()));
        assert(0 <= j1 && j1 <= j2 && j2 < static_cast<long long>(hash[0].size()));
        rh1.expand(i2 - i1);
        rh2.expand(j2 - j1);
        ull p1 = rh1.power[i2 - i1], p2 = rh2.power[j2 - j1];
        ull res = sub(hash[i2][j2], mul(hash[i1][j2], p1));
        res = sub(res, mul(hash[i2][j1], p2));
        return add(res, mul(mul(hash[i1][j1], p1), p2));
    }
};

/**
 * @brief 表 text の中で、表 pattern と一致する部分の左上の位置 (行, 列) をすべて求める O(HW + hw)
 *
 * 2 次元のローリングハッシュで比べる。行の昇順、同じ行なら列の昇順に並べる
 * pattern は 1 行 1 列以上であること
 */
template <typename Grid1, typename Grid2>
std::vector<std::pair<long long, long long>> pattern_match_2d(const Grid1& text, const Grid2& pattern) {
    using std::size;
    const long long h = size(text), w = h == 0 ? 0 : size(text[0]);
    const long long ph = size(pattern), pw = ph == 0 ? 0 : size(pattern[0]);
    assert(ph > 0 && pw > 0);
    std::vector<std::pair<long long, long long>> res;
    if (ph > h || pw > w) return res;
    RollingHash2D rh;
    auto th = rh.build(text), pht = rh.build(pattern);
    unsigned long long target = rh.query(pht, Grid(ph, pw));
    for (auto [i, j] : Grid(h - ph + 1, w - pw + 1)) {
        if (rh.query(th, Grid({i, i + ph}, {j, j + pw})) == target) res.emplace_back(i, j);
    }
    return res;
}
#line 7 "test/aoj/alds1/alds1-14-b.1.test.cpp"

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::string t, p;
    std::cin >> t >> p;
    RollingHash rh;
    auto ht = rh.build(t);
    auto hp = rh.build(p);
    int n = t.size(), m = p.size();
    unsigned long long target = rh.query(hp, 0, m);
    for (int i = 0; i + m <= n; i++) {
        if (rh.query(ht, i, i + m) == target) std::cout << i << '\n';
    }
}
Back to top page