結果

問題 No.2305 [Cherry 5th Tune N] Until That Day...
ユーザー hitonanodehitonanode
提出日時 2023-05-19 22:33:37
言語 C++23
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 25,025 bytes
コンパイル時間 3,274 ms
コンパイル使用メモリ 212,696 KB
実行使用メモリ 65,780 KB
最終ジャッジ日時 2024-12-18 03:26:44
合計ジャッジ時間 37,033 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
39,560 KB
testcase_01 AC 2 ms
6,820 KB
testcase_02 AC 2 ms
6,816 KB
testcase_03 AC 18 ms
10,616 KB
testcase_04 AC 9 ms
6,904 KB
testcase_05 AC 18 ms
10,624 KB
testcase_06 AC 135 ms
18,100 KB
testcase_07 AC 449 ms
18,264 KB
testcase_08 AC 408 ms
18,140 KB
testcase_09 AC 386 ms
18,136 KB
testcase_10 AC 378 ms
18,136 KB
testcase_11 TLE -
testcase_12 TLE -
testcase_13 AC 2,030 ms
32,844 KB
testcase_14 AC 2,303 ms
32,820 KB
testcase_15 AC 370 ms
6,816 KB
testcase_16 AC 375 ms
6,816 KB
testcase_17 AC 2 ms
6,816 KB
testcase_18 AC 3,473 ms
32,824 KB
testcase_19 AC 387 ms
18,264 KB
testcase_20 AC 669 ms
65,780 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T, typename V>
void ndarray(vector<T>& vec, const V& val, int len) { vec.assign(len, val); }
template <typename T, typename V, typename... Args> void ndarray(vector<T>& vec, const V& val, int len, Args... args) { vec.resize(len), for_each(begin(vec), end(vec), [&](T& v) { ndarray(v, val, args...); }); }
template <typename T> bool chmax(T &m, const T q) { return m < q ? (m = q, true) : false; }
template <typename T> bool chmin(T &m, const T q) { return m > q ? (m = q, true) : false; }
const std::vector<std::pair<int, int>> grid_dxs{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int floor_lg(long long x) { return x <= 0 ? -1 : 63 - __builtin_clzll(x); }
template <class T1, class T2> T1 floor_div(T1 num, T2 den) { return (num > 0 ? num / den : -((-num + den - 1) / den)); }
template <class T1, class T2> std::pair<T1, T2> operator+(const std::pair<T1, T2> &l, const std::pair<T1, T2> &r) { return std::make_pair(l.first + r.first, l.second + r.second); }
template <class T1, class T2> std::pair<T1, T2> operator-(const std::pair<T1, T2> &l, const std::pair<T1, T2> &r) { return std::make_pair(l.first - r.first, l.second - r.second); }
template <class T> std::vector<T> sort_unique(std::vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <class T> int arglb(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x)); }
template <class T> int argub(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::upper_bound(v.begin(), v.end(), x)); }
template <class IStream, class T> IStream &operator>>(IStream &is, std::vector<T> &vec) { for (auto &v : vec) is >> v; return is; }

template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec);
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr);
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const pair<T, U> &pa);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec);
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec);
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa);
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp);
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp);
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl);

template <class OStream, class T> OStream &operator<<(OStream &os, const std::vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T, size_t sz> OStream &operator<<(OStream &os, const std::array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
template <class... T> std::istream &operator>>(std::istream &is, std::tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <class OStream, class... T> OStream &operator<<(OStream &os, const std::tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
template <class OStream, class T, class TH> OStream &operator<<(OStream &os, const std::unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T> OStream &operator<<(OStream &os, const std::unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <class OStream, class T, class U> OStream &operator<<(OStream &os, const std::pair<T, U> &pa) { return os << '(' << pa.first << ',' << pa.second << ')'; }
template <class OStream, class TK, class TV> OStream &operator<<(OStream &os, const std::map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <class OStream, class TK, class TV, class TH> OStream &operator<<(OStream &os, const std::unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef HITONANODE_LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl
#define dbgif(cond, x) ((cond) ? std::cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << std::endl : std::cerr)
#else
#define dbg(x) ((void)0)
#define dbgif(cond, x) ((void)0)
#endif

#include <iostream>
#include <set>
#include <vector>

template <int md> struct ModInt {
#if __cplusplus >= 201402L
#define MDCONST constexpr
#else
#define MDCONST
#endif
    using lint = long long;
    MDCONST static int mod() { return md; }
    static int get_primitive_root() {
        static int primitive_root = 0;
        if (!primitive_root) {
            primitive_root = [&]() {
                std::set<int> fac;
                int v = md - 1;
                for (lint i = 2; i * i <= v; i++)
                    while (v % i == 0) fac.insert(i), v /= i;
                if (v > 1) fac.insert(v);
                for (int g = 1; g < md; g++) {
                    bool ok = true;
                    for (auto i : fac)
                        if (ModInt(g).pow((md - 1) / i) == 1) {
                            ok = false;
                            break;
                        }
                    if (ok) return g;
                }
                return -1;
            }();
        }
        return primitive_root;
    }
    int val_;
    int val() const noexcept { return val_; }
    MDCONST ModInt() : val_(0) {}
    MDCONST ModInt &_setval(lint v) { return val_ = (v >= md ? v - md : v), *this; }
    MDCONST ModInt(lint v) { _setval(v % md + md); }
    MDCONST explicit operator bool() const { return val_ != 0; }
    MDCONST ModInt operator+(const ModInt &x) const {
        return ModInt()._setval((lint)val_ + x.val_);
    }
    MDCONST ModInt operator-(const ModInt &x) const {
        return ModInt()._setval((lint)val_ - x.val_ + md);
    }
    MDCONST ModInt operator*(const ModInt &x) const {
        return ModInt()._setval((lint)val_ * x.val_ % md);
    }
    MDCONST ModInt operator/(const ModInt &x) const {
        return ModInt()._setval((lint)val_ * x.inv().val() % md);
    }
    MDCONST ModInt operator-() const { return ModInt()._setval(md - val_); }
    MDCONST ModInt &operator+=(const ModInt &x) { return *this = *this + x; }
    MDCONST ModInt &operator-=(const ModInt &x) { return *this = *this - x; }
    MDCONST ModInt &operator*=(const ModInt &x) { return *this = *this * x; }
    MDCONST ModInt &operator/=(const ModInt &x) { return *this = *this / x; }
    friend MDCONST ModInt operator+(lint a, const ModInt &x) {
        return ModInt()._setval(a % md + x.val_);
    }
    friend MDCONST ModInt operator-(lint a, const ModInt &x) {
        return ModInt()._setval(a % md - x.val_ + md);
    }
    friend MDCONST ModInt operator*(lint a, const ModInt &x) {
        return ModInt()._setval(a % md * x.val_ % md);
    }
    friend MDCONST ModInt operator/(lint a, const ModInt &x) {
        return ModInt()._setval(a % md * x.inv().val() % md);
    }
    MDCONST bool operator==(const ModInt &x) const { return val_ == x.val_; }
    MDCONST bool operator!=(const ModInt &x) const { return val_ != x.val_; }
    MDCONST bool operator<(const ModInt &x) const {
        return val_ < x.val_;
    } // To use std::map<ModInt, T>
    friend std::istream &operator>>(std::istream &is, ModInt &x) {
        lint t;
        return is >> t, x = ModInt(t), is;
    }
    MDCONST friend std::ostream &operator<<(std::ostream &os, const ModInt &x) {
        return os << x.val_;
    }
    MDCONST ModInt pow(lint n) const {
        ModInt ans = 1, tmp = *this;
        while (n) {
            if (n & 1) ans *= tmp;
            tmp *= tmp, n >>= 1;
        }
        return ans;
    }

    static std::vector<ModInt> facs, facinvs, invs;
    MDCONST static void _precalculation(int N) {
        int l0 = facs.size();
        if (N > md) N = md;
        if (N <= l0) return;
        facs.resize(N), facinvs.resize(N), invs.resize(N);
        for (int i = l0; i < N; i++) facs[i] = facs[i - 1] * i;
        facinvs[N - 1] = facs.back().pow(md - 2);
        for (int i = N - 2; i >= l0; i--) facinvs[i] = facinvs[i + 1] * (i + 1);
        for (int i = N - 1; i >= l0; i--) invs[i] = facinvs[i] * facs[i - 1];
    }
    MDCONST ModInt inv() const {
        if (this->val_ < std::min(md >> 1, 1 << 21)) {
            if (facs.empty()) facs = {1}, facinvs = {1}, invs = {0};
            while (this->val_ >= int(facs.size())) _precalculation(facs.size() * 2);
            return invs[this->val_];
        } else {
            return this->pow(md - 2);
        }
    }
    MDCONST ModInt fac() const {
        while (this->val_ >= int(facs.size())) _precalculation(facs.size() * 2);
        return facs[this->val_];
    }
    MDCONST ModInt facinv() const {
        while (this->val_ >= int(facs.size())) _precalculation(facs.size() * 2);
        return facinvs[this->val_];
    }
    MDCONST ModInt doublefac() const {
        lint k = (this->val_ + 1) / 2;
        return (this->val_ & 1) ? ModInt(k * 2).fac() / (ModInt(2).pow(k) * ModInt(k).fac())
                                : ModInt(k).fac() * ModInt(2).pow(k);
    }
    MDCONST ModInt nCr(const ModInt &r) const {
        return (this->val_ < r.val_) ? 0 : this->fac() * (*this - r).facinv() * r.facinv();
    }
    MDCONST ModInt nPr(const ModInt &r) const {
        return (this->val_ < r.val_) ? 0 : this->fac() * (*this - r).facinv();
    }

    ModInt sqrt() const {
        if (val_ == 0) return 0;
        if (md == 2) return val_;
        if (pow((md - 1) / 2) != 1) return 0;
        ModInt b = 1;
        while (b.pow((md - 1) / 2) == 1) b += 1;
        int e = 0, m = md - 1;
        while (m % 2 == 0) m >>= 1, e++;
        ModInt x = pow((m - 1) / 2), y = (*this) * x * x;
        x *= (*this);
        ModInt z = b.pow(m);
        while (y != 1) {
            int j = 0;
            ModInt t = y;
            while (t != 1) j++, t *= t;
            z = z.pow(1LL << (e - j - 1));
            x *= z, z *= z, y *= z;
            e = j;
        }
        return ModInt(std::min(x.val_, md - x.val_));
    }
};
template <int md> std::vector<ModInt<md>> ModInt<md>::facs = {1};
template <int md> std::vector<ModInt<md>> ModInt<md>::facinvs = {1};
template <int md> std::vector<ModInt<md>> ModInt<md>::invs = {0};

using mint = ModInt<998244353>;


// Berlekamp–Massey algorithm
// https://en.wikipedia.org/wiki/Berlekamp%E2%80%93Massey_algorithm
// Complexity: O(N^2)
// input: S = sequence from field K
// return: L          = degree of minimal polynomial,
//         C_reversed = monic min. polynomial (size = L + 1, reversed order, C_reversed[0] = 1))
// Formula: convolve(S, C_reversed)[i] = 0 for i >= L
// Example:
// - [1, 2, 4, 8, 16]   -> (1, [1, -2])
// - [1, 1, 2, 3, 5, 8] -> (2, [1, -1, -1])
// - [0, 0, 0, 0, 1]    -> (5, [1, 0, 0, 0, 0, 998244352]) (mod 998244353)
// - []                 -> (0, [1])
// - [0, 0, 0]          -> (0, [1])
// - [-2]               -> (1, [1, 2])
template <typename Tfield>
std::pair<int, std::vector<Tfield>> find_linear_recurrence(const std::vector<Tfield> &S) {
    int N = S.size();
    using poly = std::vector<Tfield>;
    poly C_reversed{1}, B{1};
    int L = 0, m = 1;
    Tfield b = 1;

    // adjust: C(x) <- C(x) - (d / b) x^m B(x)
    auto adjust = [](poly C, const poly &B, Tfield d, Tfield b, int m) -> poly {
        C.resize(std::max(C.size(), B.size() + m));
        Tfield a = d / b;
        for (unsigned i = 0; i < B.size(); i++) C[i + m] -= a * B[i];
        return C;
    };

    for (int n = 0; n < N; n++) {
        Tfield d = S[n];
        for (int i = 1; i <= L; i++) d += C_reversed[i] * S[n - i];

        if (d == 0)
            m++;
        else if (2 * L <= n) {
            poly T = C_reversed;
            C_reversed = adjust(C_reversed, B, d, b, m);
            L = n + 1 - L;
            B = T;
            b = d;
            m = 1;
        } else
            C_reversed = adjust(C_reversed, B, d, b, m++);
    }
    return std::make_pair(L, C_reversed);
}

// Calculate ^N \bmod f(x)$
// Known as `Kitamasa method`
// Input: f_reversed: monic, reversed (f_reversed[0] = 1)
// Complexity: (K^2 \log N)$ ($: deg. of $)
// Example: (4, [1, -1, -1]) -> [2, 3]
//          ( x^4 = (x^2 + x + 2)(x^2 - x - 1) + 3x + 2 )
// Reference: http://misawa.github.io/others/fast_kitamasa_method.html
//            http://sugarknri.hatenablog.com/entry/2017/11/18/233936
template <typename Tfield>
std::vector<Tfield> monomial_mod_polynomial(long long N, const std::vector<Tfield> &f_reversed) {
    assert(!f_reversed.empty() and f_reversed[0] == 1);
    int K = f_reversed.size() - 1;
    if (!K) return {};
    int D = 64 - __builtin_clzll(N);
    std::vector<Tfield> ret(K, 0);
    ret[0] = 1;
    auto self_conv = [](std::vector<Tfield> x) -> std::vector<Tfield> {
        int d = x.size();
        std::vector<Tfield> ret(d * 2 - 1);
        for (int i = 0; i < d; i++) {
            ret[i * 2] += x[i] * x[i];
            for (int j = 0; j < i; j++) ret[i + j] += x[i] * x[j] * 2;
        }
        return ret;
    };
    for (int d = D; d--;) {
        ret = self_conv(ret);
        for (int i = 2 * K - 2; i >= K; i--) {
            for (int j = 1; j <= K; j++) ret[i - j] -= ret[i] * f_reversed[j];
        }
        ret.resize(K);
        if ((N >> d) & 1) {
            std::vector<Tfield> c(K);
            c[0] = -ret[K - 1] * f_reversed[K];
            for (int i = 1; i < K; i++) { c[i] = ret[i - 1] - ret[K - 1] * f_reversed[K - i]; }
            ret = c;
        }
    }
    return ret;
}

// Guess k-th element of the sequence, assuming linear recurrence
// initial_elements: 0-ORIGIN
// Verify: abc198f https://atcoder.jp/contests/abc198/submissions/21837815
template <typename Tfield>
Tfield guess_kth_term(const std::vector<Tfield> &initial_elements, long long k) {
    assert(k >= 0);
    if (k < static_cast<long long>(initial_elements.size())) return initial_elements[k];
    const auto f = find_linear_recurrence<Tfield>(initial_elements).second;
    const auto g = monomial_mod_polynomial<Tfield>(k, f);
    Tfield ret = 0;
    for (unsigned i = 0; i < g.size(); i++) ret += g[i] * initial_elements[i];
    return ret;
}


#include <chrono>
#include <random>
#include <vector>

template <typename ModInt> std::vector<ModInt> gen_random_vector(int len) {
    static std::mt19937 mt(std::chrono::steady_clock::now().time_since_epoch().count());
    static std::uniform_int_distribution<int> rnd(1, ModInt::mod() - 1);
    std::vector<ModInt> ret(len);
    for (auto &x : ret) x = rnd(mt);
    return ret;
};

// Probabilistic algorithm to find a solution of linear equation Ax = b if exists.
// Complexity: O(n T(n) + n^2)
// Reference:
// [1] W. Eberly, E. Kaltofen, "On randomized Lanczos algorithms," Proc. of international symposium on
//     Symbolic and algebraic computation, 176-183, 1997.
template <typename Matrix, typename T>
std::vector<T> linear_system_solver_lanczos(const Matrix &A, const std::vector<T> &b) {
    assert(A.height() == int(b.size()));
    const int M = A.height(), N = A.width();

    const std::vector<T> D1 = gen_random_vector<T>(N), D2 = gen_random_vector<T>(M),
                         v = gen_random_vector<T>(N);
    auto applyD1 = [&D1](std::vector<T> v) {
        for (int i = 0; i < int(v.size()); i++) v[i] *= D1[i];
        return v;
    };
    auto applyD2 = [&D2](std::vector<T> v) {
        for (int i = 0; i < int(v.size()); i++) v[i] *= D2[i];
        return v;
    };
    auto applyAtilde = [&](std::vector<T> v) -> std::vector<T> {
        v = applyD1(v);
        v = A.prod(v);
        v = applyD2(v);
        v = A.prod_left(v);
        v = applyD1(v);
        return v;
    };
    auto dot = [&](const std::vector<T> &vl, const std::vector<T> &vr) -> T {
        return std::inner_product(vl.begin(), vl.end(), vr.begin(), T(0));
    };
    auto scalar_vec = [&](const T &x, std::vector<T> vec) -> std::vector<T> {
        for (auto &v : vec) v *= x;
        return vec;
    };

    auto btilde1 = applyD1(A.prod_left(applyD2(b))), btilde2 = applyAtilde(v);
    std::vector<T> btilde(N);
    for (int i = 0; i < N; i++) btilde[i] = btilde1[i] + btilde2[i];

    std::vector<T> w0 = btilde, v1 = applyAtilde(w0);
    std::vector<T> wm1(w0.size()), v0(v1.size());
    T t0 = dot(v1, w0), gamma = dot(btilde, w0) / t0, tm1 = 1;
    std::vector<T> x = scalar_vec(gamma, w0);
    while (true) {
        if (!t0 or !std::count_if(w0.begin(), w0.end(), [](T x) { return x != T(0); })) break;
        T alpha = dot(v1, v1) / t0, beta = dot(v1, v0) / tm1;
        std::vector<T> w1(N);
        for (int i = 0; i < N; i++) w1[i] = v1[i] - alpha * w0[i] - beta * wm1[i];
        std::vector<T> v2 = applyAtilde(w1);
        T t1 = dot(w1, v2);
        gamma = dot(btilde, w1) / t1;
        for (int i = 0; i < N; i++) x[i] += gamma * w1[i];

        wm1 = w0, w0 = w1;
        v0 = v1, v1 = v2;
        tm1 = t0, t0 = t1;
    }
    for (int i = 0; i < N; i++) x[i] -= v[i];
    return applyD1(x);
}

// Probabilistic algorithm to calculate determinant of matrices
// Complexity: O(n T(n) + n^2)
// Reference:
// [1] D. H. Wiedmann, "Solving sparse linear equations over finite fields,"
//     IEEE Trans. on Information Theory, 32(1), 54-62, 1986.
template <class Matrix, class Tp> Tp blackbox_determinant(const Matrix &M) {
    assert(M.height() == M.width());
    const int N = M.height();
    std::vector<Tp> b = gen_random_vector<Tp>(N), u = gen_random_vector<Tp>(N),
                    D = gen_random_vector<Tp>(N);
    std::vector<Tp> uMDib(2 * N);
    for (int i = 0; i < 2 * N; i++) {
        uMDib[i] = std::inner_product(u.begin(), u.end(), b.begin(), Tp(0));
        for (int j = 0; j < N; j++) b[j] *= D[j];
        b = M.prod(b);
    }
    auto ret = find_linear_recurrence<Tp>(uMDib);
    Tp det = ret.second.back() * (N % 2 ? -1 : 1);
    Tp ddet = 1;
    for (auto d : D) ddet *= d;
    return det / ddet;
}

// Complexity: O(n T(n) + n^2)
template <class Matrix, class Tp>
std::vector<Tp> reversed_minimal_polynomial_of_matrix(const Matrix &M) {
    assert(M.height() == M.width());
    const int N = M.height();
    std::vector<Tp> b = gen_random_vector<Tp>(N), u = gen_random_vector<Tp>(N);
    std::vector<Tp> uMb(2 * N);
    for (int i = 0; i < 2 * N; i++) {
        uMb[i] = std::inner_product(u.begin(), u.end(), b.begin(), Tp());
        b = M.prod(b);
    }
    auto ret = find_linear_recurrence<Tp>(uMb);
    return ret.second;
}

// Calculate A^k b
// Complexity: O(n^2 log k + n T(n))
// Verified: https://www.codechef.com/submit/COUNTSEQ2
template <class Matrix, class Tp>
std::vector<Tp> blackbox_matrix_pow_vec(const Matrix &A, long long k, std::vector<Tp> b) {
    assert(A.width() == int(b.size()));
    assert(k >= 0);

    std::vector<Tp> rev_min_poly = reversed_minimal_polynomial_of_matrix<Matrix, Tp>(A);
    std::vector<Tp> remainder = monomial_mod_polynomial<Tp>(k, rev_min_poly);

    std::vector<Tp> ret(b.size());
    for (Tp c : remainder) {
        for (int d = 0; d < int(b.size()); ++d) ret[d] += b[d] * c;
        b = A.prod(b);
    }
    return ret;
}


// Sparse matrix
template <typename Tp> struct sparse_matrix {
    int H, W;
    std::vector<std::vector<std::pair<int, Tp>>> vals;
    sparse_matrix(int H = 0, int W = 0) : H(H), W(W), vals(H) {}
    int height() const { return H; }
    int width() const { return W; }
    void add_element(int i, int j, Tp val) {
        assert(i >= 0 and i < H);
        assert(j >= 0 and i < W);
        vals[i].emplace_back(j, val);
    }
    std::vector<Tp> prod(const std::vector<Tp> &vec) const {
        assert(W == int(vec.size()));
        std::vector<Tp> ret(H);
        for (int i = 0; i < H; i++) {
            for (const auto &p : vals[i]) ret[i] += p.second * vec[p.first];
        }
        return ret;
    }
    std::vector<Tp> prod_left(const std::vector<Tp> &vec) const {
        assert(H == int(vec.size()));
        std::vector<Tp> ret(W);
        for (int i = 0; i < H; i++) {
            for (const auto &p : vals[i]) ret[p.first] += p.second * vec[i];
        }
        return ret;
    }
    std::vector<std::vector<Tp>> vecvec() const {
        std::vector<std::vector<Tp>> ret(H, std::vector<Tp>(W));
        for (int i = 0; i < H; i++) {
            for (auto p : vals[i]) ret[i][p.first] += p.second;
        }
        return ret;
    }
};


int main() {
    int N;
    cin >> N;

    vector<int> P(N + 1, -1);
    vector<vector<int>> child(N + 1);
    FOR(i, 1, N + 1) cin >> P.at(i), child.at(P.at(i)).push_back(i);
    vector<mint> W(N + 1);
    FOR(i, 1, N + 1) cin >> W.at(i);

    int Q;
    cin >> Q;

    sparse_matrix<mint> trans(N + 1 + Q, N + 1 + Q);
    REP(i, N + 1) {
        if (child.at(i).empty()) {
            trans.add_element(0, i, 1);
        } else {
            mint wsum = 0;
            for (int j : child.at(i)) wsum += W.at(j);
            for (int j : child.at(i)) trans.add_element(j, i, W.at(j) / wsum);
        }
    }


    vector<tuple<int, int, int>> kaqs;
    REP(q, Q) {
        int a, k;
        cin >> a >> k;
        kaqs.emplace_back(k, a, q);
        trans.add_element(N + 1 + q, a, 1);
        trans.add_element(N + 1 + q, N + 1 + q, 1);
    }


    vector<mint> init(N + 1);
    init.front() = 1;
    for (auto [k, a, q] : kaqs) init.push_back(a == 0 ? -1 : 0);

    vector<mint> ret(Q);

    sort(ALL(kaqs));

    int klast = -1;

    const auto rev_min_poly = reversed_minimal_polynomial_of_matrix<decltype(trans), mint>(trans);

    for (auto [k_, a, q] : kaqs) {
        auto dk = k_ - klast;
        dbg(make_tuple(k_, dk, a, q));
        klast = k_;

        if (dk) {
            auto remainder = monomial_mod_polynomial<mint>(dk, rev_min_poly);

            std::vector<mint> tmp(init.size());
            for (auto c : remainder) {
                for (int d = 0; d < int(init.size()); ++d) tmp[d] += init[d] * c;
                init = trans.prod(init);
            }
            init = tmp;
        }

        ret.at(q) = init.at(N + 1 + q);
    }

    for (auto x : ret) cout << x << endl;

    // while (Q--) {
    //     int a, k;
    //     cin >> a >> k;
    //     vector<mint> init(N + 2);
    //     init.at(0) = 1;
    //     auto trans2 = trans;
    //     trans2.add_element(N + 1, a, 1);
    //     auto ret = blackbox_matrix_pow_vec(trans2, k + 1, init);
    //     cout << ret.back() - (a == 0) << endl;
    // }
}
0