sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

G - Wildcard Construction(Verify/current/submissions/dfa_minimization_wildcard.cpp)

Verify/current/submissions/dfa_minimization_wildcard.cpp · ソース

Depends on

Code

#define SKIP_RUNTIME_CHECKS
// Verify-SHA256: bd613f001d581de704bc3b3c86ad0996330dcdb45d0a44e6921be46b93360624
#define NDEBUG
// Verify: https://atcoder.jp/contests/abc484/tasks/abc484_g

// Library: String/DFA_Minimization.cpp
// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/dfa_minimization.md
//
// API一覧
// minimize_dfa(alphabet, transitions, accepting, start=0): 到達可能な部分を同じ言語の最小DFAに変換。
// 元の状態数N>=1、文字種数A>=0。遷移は transitions[state*A+symbol]、受理フラグは0以外で受理。
// 戻り値の初期状態は0。state_map[v]は元の状態vの変換先、到達不能はkUnreachable。
// DfaMinimization::size()/alphabet()/transition(v,c)/accepting(v)はO(1)、state_map()はconst span。
// O(N*(1+A)*(1+log N))時間、O(N*(1+A))領域。遷移は全状態・全文字に対して定義する。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <numeric>
#include <span>
#include <stdexcept>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_DFA_MINIMIZATION_DEFINED
#define SIRKIT_DFA_MINIMIZATION_DEFINED

class DfaMinimization
{
    friend DfaMinimization minimize_dfa(std::size_t, std::span<const std::size_t>,
                                        std::span<const std::uint8_t>, std::size_t);
    std::size_t alphabet_ = 0;
    std::vector<std::size_t> transitions_, state_map_;
    std::vector<std::uint8_t> accepting_;

public:
    static constexpr std::size_t kUnreachable = std::numeric_limits<std::size_t>::max();

    [[nodiscard]] std::size_t size() const noexcept
    {
        return accepting_.size();
    }

    [[nodiscard]] std::size_t alphabet() const noexcept
    {
        return alphabet_;
    }

    [[nodiscard]] std::span<const std::size_t> state_map() const noexcept
    {
        return state_map_;
    }

    [[nodiscard]] std::size_t transition(std::size_t state, std::size_t symbol) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (state >= size() || symbol >= alphabet_)
        {
            throw std::out_of_range("DfaMinimization::transition: state or symbol");
        }
#endif
        return transitions_[state * alphabet_ + symbol];
    }

    [[nodiscard]] bool accepting(std::size_t state) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (state >= size())
        {
            throw std::out_of_range("DfaMinimization::accepting: state");
        }
#endif
        return accepting_[state] != 0;
    }
};

namespace detail
{
struct DfaClassRange
{
    std::size_t first, last;

    [[nodiscard]] std::size_t size() const noexcept
    {
        return last - first;
    }
};

struct DfaReverseColumn
{
    std::vector<std::size_t> offsets, vertices;
};

inline std::vector<DfaReverseColumn> ReverseReachableDfa(
    std::size_t alphabet, std::span<const std::size_t> transitions,
    std::span<const std::size_t> reachable, std::span<const std::size_t> index)
{
    const auto n = reachable.size();
    std::vector<DfaReverseColumn> reverse(alphabet);
    for (std::size_t c = 0; c < alphabet; ++c)
    {
        auto &[offsets, vertices] = reverse[c];
        offsets.resize(n + 1);
        vertices.resize(n);
        for (const auto v : reachable)
        {
            ++offsets[index[transitions[v * alphabet + c]] + 1];
        }
        std::partial_sum(offsets.begin(), offsets.end(), offsets.begin());
        std::vector<std::size_t> cursor(offsets);
        for (std::size_t i = 0; i < n; ++i)
        {
            const auto next = index[transitions[reachable[i] * alphabet + c]];
            vertices[cursor[next]++] = i;
        }
    }
    return reverse;
}

inline void RefineDfaPartition(std::span<const DfaReverseColumn> reverse,
                               std::vector<std::size_t> &order, std::vector<std::size_t> &owner,
                               std::vector<DfaClassRange> &groups)
{
    const auto n = order.size();
    std::vector<std::size_t> position(n), marked(n), from, affected;
    for (std::size_t i = 0; i < n; ++i)
    {
        position[order[i]] = i;
    }
    std::vector<std::pair<std::size_t, std::size_t>> pending;
    const auto schedule = [&](std::size_t group)
    {
        for (std::size_t c = 0; c < reverse.size(); ++c)
        {
            pending.emplace_back(group, c);
        }
    };
    schedule(groups[0].size() <= groups[1].size() ? 0 : 1);
    while (!pending.empty())
    {
        const auto [splitter, symbol] = pending.back();
        pending.pop_back();
        const auto &[offsets, vertices] = reverse[symbol];
        const auto [begin, end] = groups[splitter];

        // 区間を並べ替える前に、分割に使う前駆集合を確定する。
        from.clear();
        for (std::size_t i = begin; i < end; ++i)
        {
            const auto v = order[i];
            from.insert(from.end(), vertices.begin() + offsets[v], vertices.begin() + offsets[v + 1]);
        }

        affected.clear();
        for (const auto v : from)
        {
            const auto id = owner[v];
            if (marked[id] == 0)
            {
                affected.push_back(id);
            }
            const auto destination = groups[id].first + marked[id]++;
            const auto other = order[destination];
            order[position[v]] = other;
            position[other] = position[v];
            order[destination] = v;
            position[v] = destination;
        }

        for (const auto id : affected)
        {
            const auto count = std::exchange(marked[id], 0);
            const auto old = groups[id];
            if (count == old.size())
            {
                continue;
            }
            const auto cut = old.first + count;
            DfaClassRange smaller{old.first, cut}, larger{cut, old.last};
            if (smaller.size() > larger.size())
            {
                std::swap(smaller, larger);
            }
            const auto added = groups.size();
            groups[id] = larger;
            groups.push_back(smaller);
            for (std::size_t i = smaller.first; i < smaller.last; ++i)
            {
                owner[order[i]] = added;
            }
            // 既存の予定は大きい方を引き継ぎ、小さい方だけ新しく予定に加える。
            schedule(added);
        }
    }
}
}

[[nodiscard]] inline DfaMinimization minimize_dfa(std::size_t alphabet, std::span<const std::size_t> transitions,
                                                  std::span<const std::uint8_t> accepting, std::size_t start = 0)
{
    const auto states = accepting.size();
#ifndef SKIP_RUNTIME_CHECKS
    if (states == 0 || start >= states || transitions.size() / states != alphabet || transitions.size() % states != 0)
    {
        throw std::invalid_argument("minimize_dfa: state count, start, or transition table dimensions");
    }
    if (std::any_of(transitions.begin(), transitions.end(), [states](auto target)
                    {
                        return target >= states;
                    }))
    {
        throw std::out_of_range("minimize_dfa: transition target");
    }
#endif

    constexpr auto missing = DfaMinimization::kUnreachable;
    std::vector<std::size_t> index(states, missing), reachable{start};
    index[start] = 0;
    for (std::size_t i = 0; i < reachable.size(); ++i)
    {
        const auto row = reachable[i] * alphabet;
        for (std::size_t c = 0; c < alphabet; ++c)
        {
            const auto to = transitions[row + c];
            if (index[to] == missing)
            {
                index[to] = reachable.size();
                reachable.push_back(to);
            }
        }
    }

    const auto n = reachable.size();
    std::vector<std::size_t> order(n), owner(n);
    std::iota(order.begin(), order.end(), std::size_t{0});
    const auto middle = std::partition(order.begin(), order.end(),
                                       [&](auto i)
                                       {
                                           return accepting[reachable[i]] != 0;
                                       });
    const auto cut = static_cast<std::size_t>(middle - order.begin());
    std::vector<detail::DfaClassRange> groups;
    if (cut == 0 || cut == n)
    {
        groups.push_back({0, n});
    }
    else
    {
        groups = {{0, cut}, {cut, n}};
        for (auto it = middle; it != order.end(); ++it)
        {
            owner[*it] = 1;
        }
        const auto reverse = detail::ReverseReachableDfa(alphabet, transitions, reachable, index);
        detail::RefineDfaPartition(reverse, order, owner, groups);
    }

    std::vector<std::size_t> renumber(groups.size());
    const auto start_group = owner[0];
    std::iota(renumber.begin(), renumber.end(), std::size_t{0});
    std::swap(renumber[0], renumber[start_group]);
    DfaMinimization result;
    result.alphabet_ = alphabet;
    result.state_map_.assign(states, missing);
    result.accepting_.resize(groups.size());
    result.transitions_.resize(groups.size() * alphabet);
    for (std::size_t i = 0; i < n; ++i)
    {
        result.state_map_[reachable[i]] = renumber[owner[i]];
    }
    for (std::size_t id = 0; id < groups.size(); ++id)
    {
        const auto v = reachable[order[groups[id].first]];
        result.accepting_[renumber[id]] = accepting[v] != 0;
        for (std::size_t c = 0; c < alphabet; ++c)
        {
            const auto to = transitions[v * alphabet + c];
            result.transitions_[renumber[id] * alphabet + c] = result.state_map_[to];
        }
    }
    return result;
}

#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1


// Library: String/Bitmask_NFA.cpp
// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/bitmask_nfa.md
//
// API一覧
// [BitmaskNfa<Alphabet>] 状態数・文字種数が各64以下の非決定性有限オートマトン。
// BitmaskNfa(states, initial=0): 状態数と初期状態を指定。O(states*Alphabet)。
// add_transition(from,symbol,to)/add_epsilon(from,to): 文字付き遷移/空文字遷移を追加。O(1)。
// set_accepting(state,accept=true): 受理状態を設定・解除。O(1)。
// determinize(max_states): 到達可能な状態だけを持つBitmaskDfaを生成。上限超過でlength_error。
// N=NFAの状態数、A=文字種数、D=到達可能なDFA状態数。平均O(N*A*(N+D))時間、O(A*(N+D))領域。
// [BitmaskDfa<Alphabet>] 初期状態は0。size()は状態数。accepts(word)はO(|word|)で受理判定。
// transition(state,symbol)/accepting(state): 遷移先/受理状態かどうか。O(1)。
// count_matches<T>(choices): 各位置の文字候補のビット集合から受理語の数を数える。O(D*(1+|choices|*A))時間、O(D)領域。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_BITMASK_NFA_DEFINED
#define SIRKIT_BITMASK_NFA_DEFINED

template <std::size_t Alphabet>
class BitmaskNfa;

template <std::size_t Alphabet>
class BitmaskDfa
{
    static_assert(1 <= Alphabet && Alphabet <= 64);
    friend class BitmaskNfa<Alphabet>;

    struct Row
    {
        std::array<std::size_t, Alphabet> next;
        bool accepting;
    };

    explicit BitmaskDfa(std::vector<Row> rows)
        : rows_(std::move(rows))
    {
    }

    std::vector<Row> rows_;

public:
    using Mask = std::uint64_t;
    static constexpr Mask kAllSymbols = std::numeric_limits<Mask>::max() >> (64 - Alphabet);

    [[nodiscard]] std::size_t size() const noexcept
    {
        return rows_.size();
    }

    [[nodiscard]] std::size_t transition(std::size_t state, std::size_t symbol) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (state >= size() || symbol >= Alphabet)
        {
            throw std::out_of_range("BitmaskDfa::transition: state or symbol");
        }
#endif
        return rows_[state].next[symbol];
    }

    [[nodiscard]] bool accepting(std::size_t state) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (state >= size())
        {
            throw std::out_of_range("BitmaskDfa::accepting: state");
        }
#endif
        return rows_[state].accepting;
    }

    [[nodiscard]] bool accepts(std::span<const std::size_t> word) const
    {
        if (rows_.empty())
        {
            return false;
        }
        std::size_t state = 0;
        for (const auto symbol : word)
        {
#ifndef SKIP_RUNTIME_CHECKS
            if (symbol >= Alphabet)
            {
                throw std::out_of_range("BitmaskDfa::accepts: symbol");
            }
#endif
            state = rows_[state].next[symbol];
        }
        return rows_[state].accepting;
    }

    template <class Count>
    [[nodiscard]] Count count_matches(std::span<const Mask> choices) const
    {
        if (rows_.empty())
        {
            return Count{};
        }
        std::vector<Count> counts(size()), next(size());
        counts.front() = Count{1};
        for (const auto allowed : choices)
        {
#ifndef SKIP_RUNTIME_CHECKS
            if ((allowed & ~kAllSymbols) != 0)
            {
                throw std::out_of_range("BitmaskDfa::count_matches: symbol mask");
            }
#endif
            std::fill(next.begin(), next.end(), Count{});
            for (std::size_t state = 0; state < size(); ++state)
            {
                for (Mask remaining = allowed; remaining != 0; remaining &= remaining - 1)
                {
                    next[rows_[state].next[std::countr_zero(remaining)]] += counts[state];
                }
            }
            counts.swap(next);
        }
        Count total{};
        for (std::size_t state = 0; state < size(); ++state)
        {
            if (rows_[state].accepting)
            {
                total += counts[state];
            }
        }
        return total;
    }
};

template <std::size_t Alphabet>
class BitmaskNfa
{
    static_assert(1 <= Alphabet && Alphabet <= 64);
    using Mask = std::uint64_t;
    using SymbolTargets = std::array<Mask, Alphabet>;

    struct Row
    {
        SymbolTargets next{};
        Mask epsilon = 0;
    };

    std::vector<Row> rows_;
    std::size_t initial_ = 0;
    Mask accepting_ = 0;

    [[nodiscard]] static constexpr Mask bit(std::size_t index) noexcept
    {
        return Mask{1} << index;
    }

    static std::size_t checked_size(std::size_t states, std::size_t initial)
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (states == 0 || states > 64 || initial >= states)
        {
            throw std::invalid_argument("BitmaskNfa: state count or initial state");
        }
#else
        static_cast<void>(initial);
#endif
        return states;
    }

    void check_state(std::size_t state) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (state >= rows_.size())
        {
            throw std::out_of_range("BitmaskNfa: state");
        }
#else
        static_cast<void>(state);
#endif
    }

    [[nodiscard]] std::vector<Mask> epsilon_closures() const
    {
        std::vector<Mask> closures(rows_.size());
        for (std::size_t state = 0; state < rows_.size(); ++state)
        {
            Mask reached = bit(state), frontier = reached;
            while (frontier != 0)
            {
                const auto source = std::countr_zero(frontier);
                frontier &= frontier - 1;
                const auto unseen = rows_[source].epsilon & ~reached;
                frontier |= unseen;
                reached |= unseen;
            }
            closures[state] = reached;
        }
        return closures;
    }

public:
    explicit BitmaskNfa(std::size_t states, std::size_t initial = 0)
        : rows_(checked_size(states, initial)), initial_(initial)
    {
    }

    void add_transition(std::size_t from, std::size_t symbol, std::size_t to)
    {
        check_state(from);
        check_state(to);
#ifndef SKIP_RUNTIME_CHECKS
        if (symbol >= Alphabet)
        {
            throw std::out_of_range("BitmaskNfa::add_transition: symbol");
        }
#endif
        rows_[from].next[symbol] |= bit(to);
    }

    void add_epsilon(std::size_t from, std::size_t to)
    {
        check_state(from);
        check_state(to);
        rows_[from].epsilon |= bit(to);
    }

    void set_accepting(std::size_t state, bool accept = true)
    {
        check_state(state);
        if (accept)
        {
            accepting_ |= bit(state);
        }
        else
        {
            accepting_ &= ~bit(state);
        }
    }

    [[nodiscard]] BitmaskDfa<Alphabet> determinize(
        std::size_t max_states = std::numeric_limits<std::size_t>::max()) const
    {
        using Dfa = BitmaskDfa<Alphabet>;
        if (rows_.empty())
        {
            return Dfa({});
        }
        const auto closures = epsilon_closures();
        std::vector<SymbolTargets> targets(rows_.size());
        for (std::size_t state = 0; state < rows_.size(); ++state)
        {
            for (std::size_t symbol = 0; symbol < Alphabet; ++symbol)
            {
                for (Mask reached = rows_[state].next[symbol]; reached != 0; reached &= reached - 1)
                {
                    targets[state][symbol] |= closures[std::countr_zero(reached)];
                }
            }
        }

        std::unordered_map<Mask, std::size_t> id;
        std::vector<Mask> subsets;
        std::vector<typename Dfa::Row> table;
        const auto intern = [&](Mask subset)
        {
            auto [where, fresh] = id.try_emplace(subset, subsets.size());
            if (fresh)
            {
                if (subsets.size() == max_states)
                {
                    throw std::length_error("BitmaskNfa::determinize: state limit");
                }
                subsets.push_back(subset);
            }
            return where->second;
        };
        intern(closures[initial_]);
        for (std::size_t row = 0; row < subsets.size(); ++row)
        {
            const auto subset = subsets[row];
            SymbolTargets moves{};
            for (Mask states = subset; states != 0; states &= states - 1)
            {
                const auto &next = targets[std::countr_zero(states)];
                for (std::size_t symbol = 0; symbol < Alphabet; ++symbol)
                {
                    moves[symbol] |= next[symbol];
                }
            }
            typename Dfa::Row result{{}, (subset & accepting_) != 0};
            for (std::size_t symbol = 0; symbol < Alphabet; ++symbol)
            {
                result.next[symbol] = intern(moves[symbol]);
            }
            table.push_back(result);
        }
        return Dfa(std::move(table));
    }
};

#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1


namespace sirkit {}
using namespace sirkit;

// SPDX-License-Identifier: CC0-1.0
// ACL: atcoder/modint
#ifndef ATCODER_MODINT_HPP
#define ATCODER_MODINT_HPP 1

#include <cassert>
#include <numeric>
#include <type_traits>

#ifdef _MSC_VER
#include <intrin.h>
#endif

// ACL: atcoder/internal_math
#ifndef ATCODER_INTERNAL_MATH_HPP
#define ATCODER_INTERNAL_MATH_HPP 1

#include <utility>

#ifdef _MSC_VER
#include <intrin.h>
#endif

namespace atcoder {

namespace internal {

// @param m `1 <= m`
// @return x mod m
constexpr long long safe_mod(long long x, long long m) {
    x %= m;
    if (x < 0) x += m;
    return x;
}

// Fast modular multiplication by barrett reduction
// Reference: https://en.wikipedia.org/wiki/Barrett_reduction
// NOTE: reconsider after Ice Lake
struct barrett {
    unsigned int _m;
    unsigned long long im;

    // @param m `1 <= m`
    explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}

    // @return m
    unsigned int umod() const { return _m; }

    // @param a `0 <= a < m`
    // @param b `0 <= b < m`
    // @return `a * b % m`
    unsigned int mul(unsigned int a, unsigned int b) const {
        // [1] m = 1
        // a = b = im = 0, so okay

        // [2] m >= 2
        // im = ceil(2^64 / m)
        // -> im * m = 2^64 + r (0 <= r < m)
        // let z = a*b = c*m + d (0 <= c, d < m)
        // a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im
        // c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2
        // ((ab * im) >> 64) == c or c + 1
        unsigned long long z = a;
        z *= b;
#ifdef _MSC_VER
        unsigned long long x;
        _umul128(z, im, &x);
#else
        unsigned long long x =
            (unsigned long long)(((unsigned __int128)(z)*im) >> 64);
#endif
        unsigned long long y = x * _m;
        return (unsigned int)(z - y + (z < y ? _m : 0));
    }
};

// @param n `0 <= n`
// @param m `1 <= m`
// @return `(x ** n) % m`
constexpr long long pow_mod_constexpr(long long x, long long n, int m) {
    if (m == 1) return 0;
    unsigned int _m = (unsigned int)(m);
    unsigned long long r = 1;
    unsigned long long y = safe_mod(x, m);
    while (n) {
        if (n & 1) r = (r * y) % _m;
        y = (y * y) % _m;
        n >>= 1;
    }
    return r;
}

// Reference:
// M. Forisek and J. Jancina,
// Fast Primality Testing for Integers That Fit into a Machine Word
// @param n `0 <= n`
constexpr bool is_prime_constexpr(int n) {
    if (n <= 1) return false;
    if (n == 2 || n == 7 || n == 61) return true;
    if (n % 2 == 0) return false;
    long long d = n - 1;
    while (d % 2 == 0) d /= 2;
    constexpr long long bases[3] = {2, 7, 61};
    for (long long a : bases) {
        long long t = d;
        long long y = pow_mod_constexpr(a, t, n);
        while (t != n - 1 && y != 1 && y != n - 1) {
            y = y * y % n;
            t <<= 1;
        }
        if (y != n - 1 && t % 2 == 0) {
            return false;
        }
    }
    return true;
}
template <int n> constexpr bool is_prime = is_prime_constexpr(n);

// @param b `1 <= b`
// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g
constexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {
    a = safe_mod(a, b);
    if (a == 0) return {b, 0};

    // Contracts:
    // [1] s - m0 * a = 0 (mod b)
    // [2] t - m1 * a = 0 (mod b)
    // [3] s * |m1| + t * |m0| <= b
    long long s = b, t = a;
    long long m0 = 0, m1 = 1;

    while (t) {
        long long u = s / t;
        s -= t * u;
        m0 -= m1 * u;  // |m1 * u| <= |m1| * s <= b

        // [3]:
        // (s - t * u) * |m1| + t * |m0 - m1 * u|
        // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)
        // = s * |m1| + t * |m0| <= b

        auto tmp = s;
        s = t;
        t = tmp;
        tmp = m0;
        m0 = m1;
        m1 = tmp;
    }
    // by [3]: |m0| <= b/g
    // by g != b: |m0| < b/g
    if (m0 < 0) m0 += b / s;
    return {s, m0};
}

// Compile time primitive root
// @param m must be prime
// @return primitive root (and minimum in now)
constexpr int primitive_root_constexpr(int m) {
    if (m == 2) return 1;
    if (m == 167772161) return 3;
    if (m == 469762049) return 3;
    if (m == 754974721) return 11;
    if (m == 998244353) return 3;
    int divs[20] = {};
    divs[0] = 2;
    int cnt = 1;
    int x = (m - 1) / 2;
    while (x % 2 == 0) x /= 2;
    for (int i = 3; (long long)(i)*i <= x; i += 2) {
        if (x % i == 0) {
            divs[cnt++] = i;
            while (x % i == 0) {
                x /= i;
            }
        }
    }
    if (x > 1) {
        divs[cnt++] = x;
    }
    for (int g = 2;; g++) {
        bool ok = true;
        for (int i = 0; i < cnt; i++) {
            if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {
                ok = false;
                break;
            }
        }
        if (ok) return g;
    }
}
template <int m> constexpr int primitive_root = primitive_root_constexpr(m);

// @param n `n < 2^32`
// @param m `1 <= m < 2^32`
// @return sum_{i=0}^{n-1} floor((ai + b) / m) (mod 2^64)
unsigned long long floor_sum_unsigned(unsigned long long n,
                                      unsigned long long m,
                                      unsigned long long a,
                                      unsigned long long b) {
    unsigned long long ans = 0;
    while (true) {
        if (a >= m) {
            ans += n * (n - 1) / 2 * (a / m);
            a %= m;
        }
        if (b >= m) {
            ans += n * (b / m);
            b %= m;
        }

        unsigned long long y_max = a * n + b;
        if (y_max < m) break;
        // y_max < m * (n + 1)
        // floor(y_max / m) <= n
        n = (unsigned long long)(y_max / m);
        b = (unsigned long long)(y_max % m);
        std::swap(m, a);
    }
    return ans;
}

}  // namespace internal

}  // namespace atcoder

#endif  // ATCODER_INTERNAL_MATH_HPP

// ACL: atcoder/internal_type_traits
#ifndef ATCODER_INTERNAL_TYPE_TRAITS_HPP
#define ATCODER_INTERNAL_TYPE_TRAITS_HPP 1

#include <cassert>
#include <numeric>
#include <type_traits>

namespace atcoder {

namespace internal {

#ifndef _MSC_VER
template <class T>
using is_signed_int128 =
    typename std::conditional<std::is_same<T, __int128_t>::value ||
                                  std::is_same<T, __int128>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using is_unsigned_int128 =
    typename std::conditional<std::is_same<T, __uint128_t>::value ||
                                  std::is_same<T, unsigned __int128>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using make_unsigned_int128 =
    typename std::conditional<std::is_same<T, __int128_t>::value,
                              __uint128_t,
                              unsigned __int128>;

template <class T>
using is_integral = typename std::conditional<std::is_integral<T>::value ||
                                                  is_signed_int128<T>::value ||
                                                  is_unsigned_int128<T>::value,
                                              std::true_type,
                                              std::false_type>::type;

template <class T>
using is_signed_int = typename std::conditional<(is_integral<T>::value &&
                                                 std::is_signed<T>::value) ||
                                                    is_signed_int128<T>::value,
                                                std::true_type,
                                                std::false_type>::type;

template <class T>
using is_unsigned_int =
    typename std::conditional<(is_integral<T>::value &&
                               std::is_unsigned<T>::value) ||
                                  is_unsigned_int128<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<
    is_signed_int128<T>::value,
    make_unsigned_int128<T>,
    typename std::conditional<std::is_signed<T>::value,
                              std::make_unsigned<T>,
                              std::common_type<T>>::type>::type;

#else

template <class T> using is_integral = typename std::is_integral<T>;

template <class T>
using is_signed_int =
    typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using is_unsigned_int =
    typename std::conditional<is_integral<T>::value &&
                                  std::is_unsigned<T>::value,
                              std::true_type,
                              std::false_type>::type;

template <class T>
using to_unsigned = typename std::conditional<is_signed_int<T>::value,
                                              std::make_unsigned<T>,
                                              std::common_type<T>>::type;

#endif

template <class T>
using is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;

template <class T>
using is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;

template <class T> using to_unsigned_t = typename to_unsigned<T>::type;

}  // namespace internal

}  // namespace atcoder

#endif  // ATCODER_INTERNAL_TYPE_TRAITS_HPP

namespace atcoder {

namespace internal {

struct modint_base {};
struct static_modint_base : modint_base {};

template <class T> using is_modint = std::is_base_of<modint_base, T>;
template <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;

}  // namespace internal

template <int m, std::enable_if_t<(1 <= m)>* = nullptr>
struct static_modint : internal::static_modint_base {
    using mint = static_modint;

  public:
    static constexpr int mod() { return m; }
    static mint raw(int v) {
        mint x;
        x._v = v;
        return x;
    }

    static_modint() : _v(0) {}
    template <class T, internal::is_signed_int_t<T>* = nullptr>
    static_modint(T v) {
        long long x = (long long)(v % (long long)(umod()));
        if (x < 0) x += umod();
        _v = (unsigned int)(x);
    }
    template <class T, internal::is_unsigned_int_t<T>* = nullptr>
    static_modint(T v) {
        _v = (unsigned int)(v % umod());
    }

    int val() const { return _v; }

    mint& operator++() {
        _v++;
        if (_v == umod()) _v = 0;
        return *this;
    }
    mint& operator--() {
        if (_v == 0) _v = umod();
        _v--;
        return *this;
    }
    mint operator++(int) {
        mint result = *this;
        ++*this;
        return result;
    }
    mint operator--(int) {
        mint result = *this;
        --*this;
        return result;
    }

    mint& operator+=(const mint& rhs) {
        _v += rhs._v;
        if (_v >= umod()) _v -= umod();
        return *this;
    }
    mint& operator-=(const mint& rhs) {
        _v -= rhs._v;
        if (_v >= umod()) _v += umod();
        return *this;
    }
    mint& operator*=(const mint& rhs) {
        unsigned long long z = _v;
        z *= rhs._v;
        _v = (unsigned int)(z % umod());
        return *this;
    }
    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }

    mint operator+() const { return *this; }
    mint operator-() const { return mint() - *this; }

    mint pow(long long n) const {
        assert(0 <= n);
        mint x = *this, r = 1;
        while (n) {
            if (n & 1) r *= x;
            x *= x;
            n >>= 1;
        }
        return r;
    }
    mint inv() const {
        if (prime) {
            assert(_v);
            return pow(umod() - 2);
        } else {
            auto eg = internal::inv_gcd(_v, m);
            assert(eg.first == 1);
            return eg.second;
        }
    }

    friend mint operator+(const mint& lhs, const mint& rhs) {
        return mint(lhs) += rhs;
    }
    friend mint operator-(const mint& lhs, const mint& rhs) {
        return mint(lhs) -= rhs;
    }
    friend mint operator*(const mint& lhs, const mint& rhs) {
        return mint(lhs) *= rhs;
    }
    friend mint operator/(const mint& lhs, const mint& rhs) {
        return mint(lhs) /= rhs;
    }
    friend bool operator==(const mint& lhs, const mint& rhs) {
        return lhs._v == rhs._v;
    }
    friend bool operator!=(const mint& lhs, const mint& rhs) {
        return lhs._v != rhs._v;
    }

  private:
    unsigned int _v;
    static constexpr unsigned int umod() { return m; }
    static constexpr bool prime = internal::is_prime<m>;
};

template <int id> struct dynamic_modint : internal::modint_base {
    using mint = dynamic_modint;

  public:
    static int mod() { return (int)(bt.umod()); }
    static void set_mod(int m) {
        assert(1 <= m);
        bt = internal::barrett(m);
    }
    static mint raw(int v) {
        mint x;
        x._v = v;
        return x;
    }

    dynamic_modint() : _v(0) {}
    template <class T, internal::is_signed_int_t<T>* = nullptr>
    dynamic_modint(T v) {
        long long x = (long long)(v % (long long)(mod()));
        if (x < 0) x += mod();
        _v = (unsigned int)(x);
    }
    template <class T, internal::is_unsigned_int_t<T>* = nullptr>
    dynamic_modint(T v) {
        _v = (unsigned int)(v % mod());
    }

    int val() const { return _v; }

    mint& operator++() {
        _v++;
        if (_v == umod()) _v = 0;
        return *this;
    }
    mint& operator--() {
        if (_v == 0) _v = umod();
        _v--;
        return *this;
    }
    mint operator++(int) {
        mint result = *this;
        ++*this;
        return result;
    }
    mint operator--(int) {
        mint result = *this;
        --*this;
        return result;
    }

    mint& operator+=(const mint& rhs) {
        _v += rhs._v;
        if (_v >= umod()) _v -= umod();
        return *this;
    }
    mint& operator-=(const mint& rhs) {
        _v += mod() - rhs._v;
        if (_v >= umod()) _v -= umod();
        return *this;
    }
    mint& operator*=(const mint& rhs) {
        _v = bt.mul(_v, rhs._v);
        return *this;
    }
    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }

    mint operator+() const { return *this; }
    mint operator-() const { return mint() - *this; }

    mint pow(long long n) const {
        assert(0 <= n);
        mint x = *this, r = 1;
        while (n) {
            if (n & 1) r *= x;
            x *= x;
            n >>= 1;
        }
        return r;
    }
    mint inv() const {
        auto eg = internal::inv_gcd(_v, mod());
        assert(eg.first == 1);
        return eg.second;
    }

    friend mint operator+(const mint& lhs, const mint& rhs) {
        return mint(lhs) += rhs;
    }
    friend mint operator-(const mint& lhs, const mint& rhs) {
        return mint(lhs) -= rhs;
    }
    friend mint operator*(const mint& lhs, const mint& rhs) {
        return mint(lhs) *= rhs;
    }
    friend mint operator/(const mint& lhs, const mint& rhs) {
        return mint(lhs) /= rhs;
    }
    friend bool operator==(const mint& lhs, const mint& rhs) {
        return lhs._v == rhs._v;
    }
    friend bool operator!=(const mint& lhs, const mint& rhs) {
        return lhs._v != rhs._v;
    }

  private:
    unsigned int _v;
    static internal::barrett bt;
    static unsigned int umod() { return bt.umod(); }
};
template <int id> internal::barrett dynamic_modint<id>::bt(998244353);

using modint998244353 = static_modint<998244353>;
using modint1000000007 = static_modint<1000000007>;
using modint = dynamic_modint<-1>;

namespace internal {

template <class T>
using is_static_modint = std::is_base_of<internal::static_modint_base, T>;

template <class T>
using is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;

template <class> struct is_dynamic_modint : public std::false_type {};
template <int id>
struct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};

template <class T>
using is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;

}  // namespace internal

}  // namespace atcoder

#endif  // ATCODER_MODINT_HPP

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
// Verify I/O: Verify/current/common/fast_io.hpp
// SPDX-License-Identifier: CC0-1.0
#include <algorithm>
#include <array>
#include <charconv>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>

#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<unsigned char, buffer_size + 1> 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<class T>
        requires (std::is_integral_v<T> && sizeof(T) <= sizeof(std::uint64_t)
                  && !std::is_same_v<T, char>)
    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<unsigned>(*cursor - '0') < 10) {
                value = value * 10 + static_cast<unsigned>(*cursor - '0');
                ++cursor;
            }
            position_ += static_cast<std::size_t>(cursor - first);
            if (position_ != size_) break;
            c = peek();
            if (c == EOF) break;
        }
#else
        while (c >= '0' && c <= '9') {
            previous = value;
            last_digit = static_cast<unsigned>(c - '0');
            if (digits <= 20) ++digits;
            value = value * 10 + static_cast<unsigned>(c - '0');
            ++position_;
            c = peek();
        }
#endif
#ifndef SKIP_RUNTIME_CHECKS
        constexpr auto maximum = std::numeric_limits<std::uint64_t>::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::uint64_t>(std::numeric_limits<T>::max());
        if constexpr (std::is_signed_v<T>) 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<T>) {
            constexpr std::uint64_t minimum_magnitude =
                static_cast<std::uint64_t>(std::numeric_limits<T>::max()) + 1;
            // -(最小値)は評価せず、絶対値が最大値+1のときだけ最小値を使う。
            result = negative
                ? (value == minimum_magnitude ? std::numeric_limits<T>::min()
                                  : static_cast<T>(-static_cast<T>(value)))
                : static_cast<T>(value);
        } else result = static_cast<T>(value);
        return *this;
    }

    VerifyInput& operator>>(char& result) {
        if (!good_) return *this;
        const int c = skip_space();
        if (c != EOF) {
            result = static_cast<char>(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<const char*>(buffer_.data() + first), position_ - first);
            if (position_ != size_ || peek() == EOF) break;
        }
        return *this;
    }

    template<class T> requires std::is_floating_point_v<T>
    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<T>(value);
#else
        result = static_cast<T>(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<char, buffer_size> 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<class T>
        requires (std::is_integral_v<T> && sizeof(T) <= sizeof(std::uint64_t)
                  && !std::is_same_v<T, char>)
    VerifyOutput& operator<<(T value) {
        if constexpr (std::is_same_v<T, bool>) return *this << static_cast<char>('0' + value);
        else {
            constexpr std::size_t capacity = std::numeric_limits<std::uint64_t>::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<std::size_t>(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<class T> requires std::is_floating_point_v<T>
    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<long double>(value));
        if (count < 0) good_ = false;
        else if (static_cast<std::size_t>(count) < sizeof(local))
            write(std::string_view(local, static_cast<std::size_t>(count)));
        else {
            std::vector<char> text(static_cast<std::size_t>(count) + 1);
            std::snprintf(text.data(), text.size(), format, precision_, static_cast<long double>(value));
            write(std::string_view(text.data(), static_cast<std::size_t>(count)));
        }
        return *this;
    }
};

inline VerifyInput verify_in;
inline VerifyOutput verify_out;
#endif

// Verify support: Verify/current/common/wildcard_construction.hpp
// SPDX-License-Identifier: CC0-1.0
#ifndef SIRKIT_VERIFY_WILDCARD_CONSTRUCTION_DEFINED
#define SIRKIT_VERIFY_WILDCARD_CONSTRUCTION_DEFINED

#include <cstddef>
#include <string_view>
#include <vector>

namespace verify_wildcard
{
inline sirkit::BitmaskDfa<2> automaton(std::string_view x, std::string_view y)
{
    sirkit::BitmaskNfa<2> nfa(x.size() + y.size());
    nfa.set_accepting(0);
    nfa.set_accepting(1);
    std::size_t available_state = 2;
    const auto add = [&](std::size_t source, char allowed, std::size_t destination)
    {
        for (std::size_t symbol = 0; symbol < 2; ++symbol)
        {
            if (allowed == '?' || allowed == static_cast<char>('0' + symbol))
            {
                nfa.add_transition(source, symbol, destination);
            }
        }
    };
    const auto path = [&](std::string_view word, std::size_t end, bool allowed_after_y)
    {
        std::size_t source = 0;
        for (std::size_t i = 0; i < word.size(); ++i)
        {
            const auto next = i + 1 == word.size() ? end : available_state++;
            add(source, word[i], next);
            if (i == 0 && allowed_after_y)
            {
                add(1, word[i], next);
            }
            source = next;
        }
    };
    path(x, 0, true);
    path(y, 1, false);
    return nfa.determinize();
}

inline std::vector<sirkit::BitmaskDfa<2>::Mask> masks(std::string_view text)
{
    std::vector<sirkit::BitmaskDfa<2>::Mask> choices;
    choices.reserve(text.size());
    for (const char c : text)
    {
        choices.push_back(c == '?' ? 3 : 1ULL << (c - '0'));
    }
    return choices;
}
}

#endif


int main()
{
    std::string text, x, y;
    verify_in >> text >> x >> y;
    const auto automaton = verify_wildcard::automaton(x, y);
    std::vector<std::size_t> edges(2 * automaton.size());
    std::vector<std::uint8_t> accepting(automaton.size());
    for (std::size_t state = 0; state < automaton.size(); ++state)
    {
        accepting[state] = automaton.accepting(state);
        edges[2 * state] = automaton.transition(state, 0);
        edges[2 * state + 1] = automaton.transition(state, 1);
    }
    const auto minimal = minimize_dfa(2, edges, accepting);
    using Mint = atcoder::modint998244353;
    std::vector<Mint> current(minimal.size()), next(minimal.size());
    current[0] = 1;
    for (const auto mask : verify_wildcard::masks(text))
    {
        std::fill(next.begin(), next.end(), Mint{});
        for (std::size_t v = 0; v < minimal.size(); ++v)
        {
            for (std::size_t c = 0; c < 2; ++c)
            {
                if ((mask >> c & 1) != 0)
                {
                    next[minimal.transition(v, c)] += current[v];
                }
            }
        }
        current.swap(next);
    }
    Mint answer{};
    for (std::size_t state = 0; state < minimal.size(); ++state)
    {
        if (minimal.accepting(state))
        {
            answer += current[state];
        }
    }
    verify_out << answer.val() << '\n';
}
Back to top page