QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#511120 | #9167. Coprime Array | ucup-team087# | WA | 2ms | 5204kb | C++23 | 99.6kb | 2024-08-09 16:27:54 | 2024-08-09 16:27:54 |
Judging History
answer
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <functional>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using Int = long long;
template <class T1, class T2> ostream &operator<<(ostream &os, const pair<T1, T2> &a) { return os << "(" << a.first << ", " << a.second << ")"; };
template <class T> ostream &operator<<(ostream &os, const vector<T> &as) { const int sz = as.size(); os << "["; for (int i = 0; i < sz; ++i) { if (i >= 256) { os << ", ..."; break; } if (i > 0) { os << ", "; } os << as[i]; } return os << "]"; }
template <class T> void pv(T a, T b) { for (T i = a; i != b; ++i) cerr << *i << " "; cerr << endl; }
template <class T> bool chmin(T &t, const T &f) { if (t > f) { t = f; return true; } return false; }
template <class T> bool chmax(T &t, const T &f) { if (t < f) { t = f; return true; } return false; }
#define COLOR(s) ("\x1b[" s "m")
// https://judge.yosupo.jp/submission/219012
#line 1 "cp-algorithms-aux/verify/linalg/pow_fast.test.cpp"
// @brief Pow of Matrix (Frobenius)
#define PROBLEM "https://judge.yosupo.jp/problem/pow_of_matrix"
#pragma GCC optimize("Ofast,unroll-loops")
//#pragma GCC target("tune=native")
#define CP_ALGO_MAXN 1 << 10
#line 1 "cp-algorithms-aux/cp-algo/linalg/frobenius.hpp"
#line 1 "cp-algorithms-aux/cp-algo/math/poly.hpp"
#line 1 "cp-algorithms-aux/cp-algo/math/poly/impl/euclid.hpp"
#line 1 "cp-algorithms-aux/cp-algo/math/affine.hpp"
#include <optional>
#include <utility>
#include <cassert>
#include <tuple>
namespace cp_algo::math {
// a * x + b
template<typename base>
struct lin {
base a = 1, b = 0;
std::optional<base> c;
lin() {}
lin(base b): a(0), b(b) {}
lin(base a, base b): a(a), b(b) {}
lin(base a, base b, base _c): a(a), b(b), c(_c) {}
// polynomial product modulo x^2 - c
lin operator * (const lin& t) {
assert(c && t.c && *c == *t.c);
return {a * t.b + b * t.a, b * t.b + a * t.a * (*c), *c};
}
// a * (t.a * x + t.b) + b
lin apply(lin const& t) const {
return {a * t.a, a * t.b + b};
}
void prepend(lin const& t) {
*this = t.apply(*this);
}
base eval(base x) const {
return a * x + b;
}
};
// (ax+b) / (cx+d)
template<typename base>
struct linfrac {
base a, b, c, d;
linfrac(): a(1), b(0), c(0), d(1) {} // x, identity for composition
linfrac(base a): a(a), b(1), c(1), d(0) {} // a + 1/x, for continued fractions
linfrac(base a, base b, base c, base d): a(a), b(b), c(c), d(d) {}
// composition of two linfracs
linfrac operator * (linfrac t) const {
return t.prepend(linfrac(*this));
}
linfrac operator-() const {
return {-a, -b, -c, -d};
}
linfrac adj() const {
return {d, -b, -c, a};
}
linfrac& prepend(linfrac const& t) {
t.apply(a, c);
t.apply(b, d);
return *this;
}
// apply linfrac to A/B
void apply(base &A, base &B) const {
std::tie(A, B) = std::pair{a * A + b * B, c * A + d * B};
}
};
}
#line 1 "cp-algorithms-aux/cp-algo/math/fft.hpp"
#line 1 "cp-algorithms-aux/cp-algo/math/common.hpp"
#include <functional>
#include <cstdint>
namespace cp_algo::math {
#ifdef CP_ALGO_MAXN
const int maxn = CP_ALGO_MAXN;
#else
const int maxn = 1 << 19;
#endif
const int magic = 64; // threshold for sizes to run the naive algo
auto bpow(auto const& x, int64_t n, auto const& one, auto op) {
if(n == 0) {
return one;
} else {
auto t = bpow(x, n / 2, one, op);
t = op(t, t);
if(n % 2) {
t = op(t, x);
}
return t;
}
}
auto bpow(auto x, int64_t n, auto ans) {
return bpow(x, n, ans, std::multiplies{});
}
template<typename T>
T bpow(T const& x, int64_t n) {
return bpow(x, n, T(1));
}
}
#line 1 "cp-algorithms-aux/cp-algo/math/modint.hpp"
#line 4 "cp-algorithms-aux/cp-algo/math/modint.hpp"
#include <iostream>
namespace cp_algo::math {
template<typename modint>
struct modint_base {
static int64_t mod() {
return modint::mod();
}
modint_base(): r(0) {}
modint_base(int64_t rr): r(rr % mod()) {
r = std::min(r, r + mod());
}
modint inv() const {
return bpow(to_modint(), mod() - 2);
}
modint operator - () const {return std::min(-r, mod() - r);}
modint& operator /= (const modint &t) {
return to_modint() *= t.inv();
}
modint& operator *= (const modint &t) {
if(mod() <= uint32_t(-1)) {
r = r * t.r % mod();
} else {
r = __int128(r) * t.r % mod();
}
return to_modint();
}
modint& operator += (const modint &t) {
r += t.r; r = std::min(r, r - mod());
return to_modint();
}
modint& operator -= (const modint &t) {
r -= t.r; r = std::min(r, r + mod());
return to_modint();
}
modint operator + (const modint &t) const {return modint(to_modint()) += t;}
modint operator - (const modint &t) const {return modint(to_modint()) -= t;}
modint operator * (const modint &t) const {return modint(to_modint()) *= t;}
modint operator / (const modint &t) const {return modint(to_modint()) /= t;}
auto operator <=> (const modint_base &t) const = default;
int64_t rem() const {return 2 * r > (uint64_t)mod() ? r - mod() : r;}
// Only use if you really know what you're doing!
uint64_t modmod() const {return 8ULL * mod() * mod();};
void add_unsafe(uint64_t t) {r += t;}
void pseudonormalize() {r = std::min(r, r - modmod());}
modint const& normalize() {
if(r >= (uint64_t)mod()) {
r %= mod();
}
return to_modint();
}
uint64_t& setr() {return r;}
uint64_t getr() const {return r;}
private:
uint64_t r;
modint& to_modint() {return static_cast<modint&>(*this);}
modint const& to_modint() const {return static_cast<modint const&>(*this);}
};
template<typename modint>
std::istream& operator >> (std::istream &in, modint_base<modint> &x) {
return in >> x.setr();
}
template<typename modint>
std::ostream& operator << (std::ostream &out, modint_base<modint> const& x) {
return out << x.getr();
}
template<typename modint>
concept modint_type = std::is_base_of_v<modint_base<modint>, modint>;
template<int64_t m>
struct modint: modint_base<modint<m>> {
static constexpr int64_t mod() {return m;}
using Base = modint_base<modint<m>>;
using Base::Base;
};
struct dynamic_modint: modint_base<dynamic_modint> {
static int64_t mod() {return m;}
static void switch_mod(int64_t nm) {m = nm;}
using Base = modint_base<dynamic_modint>;
using Base::Base;
// Wrapper for temp switching
auto static with_mod(int64_t tmp, auto callback) {
struct scoped {
int64_t prev = mod();
~scoped() {switch_mod(prev);}
} _;
switch_mod(tmp);
return callback();
}
private:
static int64_t m;
};
int64_t dynamic_modint::m = 0;
}
#line 5 "cp-algorithms-aux/cp-algo/math/fft.hpp"
#include <algorithm>
#include <complex>
#line 8 "cp-algorithms-aux/cp-algo/math/fft.hpp"
#include <ranges>
#include <vector>
#include <bit>
namespace cp_algo::math::fft {
using ftype = double;
static constexpr size_t bytes = 32;
static constexpr size_t flen = bytes / sizeof(ftype);
using point = std::complex<ftype>;
using vftype [[gnu::vector_size(bytes)]] = ftype;
using vpoint = std::complex<vftype>;
#define WITH_IV(...) \
[&]<size_t ... i>(std::index_sequence<i...>) { \
return __VA_ARGS__; \
}(std::make_index_sequence<flen>());
template<typename ft>
constexpr ft to_ft(auto x) {
return ft{} + x;
}
template<typename pt>
constexpr pt to_pt(point r) {
using ft = std::conditional_t<std::is_same_v<point, pt>, ftype, vftype>;
return {to_ft<ft>(r.real()), to_ft<ft>(r.imag())};
}
struct cvector {
static constexpr size_t pre_roots = 1 << 17;
std::vector<vftype> x, y;
cvector(size_t n) {
n = std::max(flen, std::bit_ceil(n));
x.resize(n / flen);
y.resize(n / flen);
}
template<class pt = point>
void set(size_t k, pt t) {
if constexpr(std::is_same_v<pt, point>) {
x[k / flen][k % flen] = real(t);
y[k / flen][k % flen] = imag(t);
} else {
x[k / flen] = real(t);
y[k / flen] = imag(t);
}
}
template<class pt = point>
pt get(size_t k) const {
if constexpr(std::is_same_v<pt, point>) {
return {x[k / flen][k % flen], y[k / flen][k % flen]};
} else {
return {x[k / flen], y[k / flen]};
}
}
vpoint vget(size_t k) const {
return get<vpoint>(k);
}
size_t size() const {
return flen * std::size(x);
}
void dot(cvector const& t) {
size_t n = size();
for(size_t k = 0; k < n; k += flen) {
set(k, get<vpoint>(k) * t.get<vpoint>(k));
}
}
static const cvector roots;
template<class pt = point>
static pt root(size_t n, size_t k) {
if(n < pre_roots) {
return roots.get<pt>(n + k);
} else {
auto arg = std::numbers::pi / n;
if constexpr(std::is_same_v<pt, point>) {
return {cos(k * arg), sin(k * arg)};
} else {
return WITH_IV(pt{vftype{cos((k + i) * arg)...},
vftype{sin((k + i) * arg)...}});
}
}
}
template<class pt = point>
static void exec_on_roots(size_t n, size_t m, auto &&callback) {
size_t step = sizeof(pt) / sizeof(point);
pt cur;
pt arg = to_pt<pt>(root<point>(n, step));
for(size_t i = 0; i < m; i += step) {
if(i % 64 == 0 || n < pre_roots) {
cur = root<pt>(n, i);
} else {
cur *= arg;
}
callback(i, cur);
}
}
void ifft() {
size_t n = size();
for(size_t i = 1; i < n; i *= 2) {
for(size_t j = 0; j < n; j += 2 * i) {
auto butterfly = [&]<class pt>(size_t k, pt rt) {
k += j;
auto t = get<pt>(k + i) * conj(rt);
set(k + i, get<pt>(k) - t);
set(k, get<pt>(k) + t);
};
if(2 * i <= flen) {
exec_on_roots(i, i, butterfly);
} else {
exec_on_roots<vpoint>(i, i, butterfly);
}
}
}
for(size_t k = 0; k < n; k += flen) {
set(k, get<vpoint>(k) /= to_pt<vpoint>(n));
}
}
void fft() {
size_t n = size();
for(size_t i = n / 2; i >= 1; i /= 2) {
for(size_t j = 0; j < n; j += 2 * i) {
auto butterfly = [&]<class pt>(size_t k, pt rt) {
k += j;
auto A = get<pt>(k) + get<pt>(k + i);
auto B = get<pt>(k) - get<pt>(k + i);
set(k, A);
set(k + i, B * rt);
};
if(2 * i <= flen) {
exec_on_roots(i, i, butterfly);
} else {
exec_on_roots<vpoint>(i, i, butterfly);
}
}
}
}
};
const cvector cvector::roots = []() {
cvector res(pre_roots);
for(size_t n = 1; n < res.size(); n *= 2) {
auto base = std::polar(1., std::numbers::pi / n);
point cur = 1;
for(size_t k = 0; k < n; k++) {
if((k & 15) == 0) {
cur = std::polar(1., std::numbers::pi * k / n);
}
res.set(n + k, cur);
cur *= base;
}
}
return res;
}();
template<typename base>
struct dft {
cvector A;
dft(std::vector<base> const& a, size_t n): A(n) {
for(size_t i = 0; i < std::min(n, a.size()); i++) {
A.set(i, a[i]);
}
if(n) {
A.fft();
}
}
std::vector<base> operator *= (dft const& B) {
assert(A.size() == B.A.size());
size_t n = A.size();
if(!n) {
return std::vector<base>();
}
A.dot(B.A);
A.ifft();
std::vector<base> res(n);
for(size_t k = 0; k < n; k++) {
res[k] = A.get(k);
}
return res;
}
auto operator * (dft const& B) const {
return dft(*this) *= B;
}
point operator [](int i) const {return A.get(i);}
};
template<modint_type base>
struct dft<base> {
int split;
cvector A, B;
dft(auto const& a, size_t n): A(n), B(n) {
split = std::sqrt(base::mod());
cvector::exec_on_roots(2 * n, size(a), [&](size_t i, point rt) {
size_t ti = std::min(i, i - n);
A.set(ti, A.get(ti) + ftype(a[i].rem() % split) * rt);
B.set(ti, B.get(ti) + ftype(a[i].rem() / split) * rt);
});
if(n) {
A.fft();
B.fft();
}
}
void mul(auto &&C, auto const& D, auto &res, size_t k) {
assert(A.size() == C.size());
size_t n = A.size();
if(!n) {
res = {};
return;
}
for(size_t i = 0; i < n; i += flen) {
auto tmp = A.vget(i) * D.vget(i) + B.vget(i) * C.vget(i);
A.set(i, A.vget(i) * C.vget(i));
B.set(i, B.vget(i) * D.vget(i));
C.set(i, tmp);
}
A.ifft();
B.ifft();
C.ifft();
auto splitsplit = (base(split) * split).rem();
cvector::exec_on_roots(2 * n, std::min(n, k), [&](size_t i, point rt) {
rt = conj(rt);
auto Ai = A.get(i) * rt;
auto Bi = B.get(i) * rt;
auto Ci = C.get(i) * rt;
int64_t A0 = llround(real(Ai));
int64_t A1 = llround(real(Ci));
int64_t A2 = llround(real(Bi));
res[i] = A0 + A1 * split + A2 * splitsplit;
if(n + i >= k) {
return;
}
int64_t B0 = llround(imag(Ai));
int64_t B1 = llround(imag(Ci));
int64_t B2 = llround(imag(Bi));
res[n + i] = B0 + B1 * split + B2 * splitsplit;
});
}
void mul_inplace(auto &&B, auto& res, size_t k) {
mul(B.A, B.B, res, k);
}
void mul(auto const& B, auto& res, size_t k) {
mul(cvector(B.A), B.B, res, k);
}
std::vector<base> operator *= (dft &B) {
std::vector<base> res(2 * A.size());
mul_inplace(B, res, size(res));
return res;
}
std::vector<base> operator *= (dft const& B) {
std::vector<base> res(2 * A.size());
mul(B, res, size(res));
return res;
}
auto operator * (dft const& B) const {
return dft(*this) *= B;
}
point operator [](int i) const {return A.get(i);}
};
void mul_slow(auto &a, auto const& b, size_t k) {
if(empty(a) || empty(b)) {
a.clear();
} else {
int n = std::min(k, size(a));
int m = std::min(k, size(b));
a.resize(k);
for(int j = k - 1; j >= 0; j--) {
a[j] *= b[0];
for(int i = std::max(j - n, 0) + 1; i < std::min(j + 1, m); i++) {
a[j] += a[j - i] * b[i];
}
}
}
}
size_t com_size(size_t as, size_t bs) {
if(!as || !bs) {
return 0;
}
return std::max(flen, std::bit_ceil(as + bs - 1) / 2);
}
void mul_truncate(auto &a, auto const& b, size_t k) {
using base = std::decay_t<decltype(a[0])>;
if(std::min({k, size(a), size(b)}) < 64) {
mul_slow(a, b, k);
return;
}
auto n = std::max(flen, std::bit_ceil(
std::min(k, size(a)) + std::min(k, size(b)) - 1
) / 2);
a.resize(k);
auto A = dft<base>(a, n);
if(&a == &b) {
A.mul(A, a, k);
} else {
A.mul_inplace(dft<base>(std::views::take(b, k), n), a, k);
}
}
void mul(auto &a, auto const& b) {
if(size(a)) {
mul_truncate(a, b, size(a) + size(b) - 1);
}
}
}
#line 7 "cp-algorithms-aux/cp-algo/math/poly/impl/euclid.hpp"
#include <numeric>
#line 11 "cp-algorithms-aux/cp-algo/math/poly/impl/euclid.hpp"
#include <list>
// operations related to gcd and Euclidean algo
namespace cp_algo::math::poly::impl {
template<typename poly>
using gcd_result = std::pair<
std::list<std::decay_t<poly>>,
linfrac<std::decay_t<poly>>>;
template<typename poly>
gcd_result<poly> half_gcd(poly &&A, poly &&B) {
assert(A.deg() >= B.deg());
int m = size(A.a) / 2;
if(B.deg() < m) {
return {};
}
auto [ai, R] = A.divmod(B);
std::tie(A, B) = {B, R};
std::list a = {ai};
auto T = -linfrac(ai).adj();
auto advance = [&](int k) {
auto [ak, Tk] = half_gcd(A.div_xk(k), B.div_xk(k));
a.splice(end(a), ak);
T.prepend(Tk);
return Tk;
};
advance(m).apply(A, B);
if constexpr (std::is_reference_v<poly>) {
advance(2 * m - A.deg()).apply(A, B);
} else {
advance(2 * m - A.deg());
}
return {std::move(a), std::move(T)};
}
template<typename poly>
gcd_result<poly> full_gcd(poly &&A, poly &&B) {
using poly_t = std::decay_t<poly>;
std::list<poly_t> ak;
std::vector<linfrac<poly_t>> trs;
while(!B.is_zero()) {
auto [a0, R] = A.divmod(B);
ak.push_back(a0);
trs.push_back(-linfrac(a0).adj());
std::tie(A, B) = {B, R};
auto [a, Tr] = half_gcd(A, B);
ak.splice(end(ak), a);
trs.push_back(Tr);
}
return {ak, std::accumulate(rbegin(trs), rend(trs), linfrac<poly_t>{}, std::multiplies{})};
}
// computes product of linfrac on [L, R)
auto convergent(auto L, auto R) {
using poly = decltype(L)::value_type;
if(R == next(L)) {
return linfrac(*L);
} else {
int s = std::transform_reduce(L, R, 0, std::plus{}, std::mem_fn(&poly::deg));
auto M = L;
for(int c = M->deg(); 2 * c <= s; M++) {
c += next(M)->deg();
}
return convergent(L, M) * convergent(M, R);
}
}
template<typename poly>
poly min_rec(poly const& p, size_t d) {
auto R2 = p.mod_xk(d).reversed(d), R1 = poly::xk(d);
if(R2.is_zero()) {
return poly(1);
}
auto [a, Tr] = full_gcd(R1, R2);
a.emplace_back();
auto pref = begin(a);
for(int delta = d - a.front().deg(); delta >= 0; pref++) {
delta -= pref->deg() + next(pref)->deg();
}
return convergent(begin(a), pref).a;
}
template<typename poly>
std::optional<poly> inv_mod(poly p, poly q) {
assert(!q.is_zero());
auto [a, Tr] = full_gcd(q, p);
if(q.deg() != 0) {
return std::nullopt;
}
return Tr.b / q[0];
}
}
#line 1 "cp-algorithms-aux/cp-algo/math/poly/impl/base.hpp"
#line 6 "cp-algorithms-aux/cp-algo/math/poly/impl/base.hpp"
// really basic operations, typically taking O(n)
namespace cp_algo::math::poly::impl {
template<typename polyn>
void normalize(polyn& p) {
while(p.deg() >= 0 && p.lead() == typename polyn::base(0)) {
p.a.pop_back();
}
}
auto neg_inplace(auto &&p) {
std::ranges::transform(p.a, begin(p.a), std::negate{});
return p;
}
auto& scale(auto &p, auto x) {
for(auto &it: p.a) {
it *= x;
}
p.normalize();
return p;
}
auto& add(auto &p, auto const& q) {
p.a.resize(std::max(p.a.size(), q.a.size()));
std::ranges::transform(p.a, q.a, begin(p.a), std::plus{});
normalize(p);
return p;
}
auto& sub(auto &p, auto const& q) {
p.a.resize(std::max(p.a.size(), q.a.size()));
std::ranges::transform(p.a, q.a, begin(p.a), std::minus{});
normalize(p);
return p;
}
auto substr(auto const& p, size_t l, size_t k) {
return std::vector(
begin(p.a) + std::min(l, p.a.size()),
begin(p.a) + std::min(l + k, p.a.size())
);
}
auto& reverse(auto &p, size_t n) {
p.a.resize(n);
std::ranges::reverse(p.a);
normalize(p);
return p;
}
}
#line 1 "cp-algorithms-aux/cp-algo/math/poly/impl/div.hpp"
#line 6 "cp-algorithms-aux/cp-algo/math/poly/impl/div.hpp"
// operations related to polynomial division
namespace cp_algo::math::poly::impl {
auto divmod_slow(auto const& p, auto const& q) {
auto R = p;
auto D = decltype(p){};
auto q_lead_inv = q.lead().inv();
while(R.deg() >= q.deg()) {
D.a.push_back(R.lead() * q_lead_inv);
if(D.lead() != 0) {
for(size_t i = 1; i <= q.a.size(); i++) {
R.a[R.a.size() - i] -= D.lead() * q.a[q.a.size() - i];
}
}
R.a.pop_back();
}
std::ranges::reverse(D.a);
R.normalize();
return std::array{D, R};
}
template<typename poly>
auto divmod_hint(poly const& p, poly const& q, poly const& qri) {
assert(!q.is_zero());
int d = p.deg() - q.deg();
if(std::min(d, q.deg()) < magic) {
return divmod_slow(p, q);
}
poly D;
if(d >= 0) {
D = (p.reversed().mod_xk(d + 1) * qri.mod_xk(d + 1)).mod_xk(d + 1).reversed(d + 1);
}
return std::array{D, p - D * q};
}
auto divmod(auto const& p, auto const& q) {
assert(!q.is_zero());
int d = p.deg() - q.deg();
if(std::min(d, q.deg()) < magic) {
return divmod_slow(p, q);
}
return divmod_hint(p, q, q.reversed().inv(d + 1));
}
template<typename poly>
poly powmod_hint(poly const& p, int64_t k, poly const& md, poly const& mdri) {
return bpow(p, k, poly(1), [&](auto const& p, auto const& q){
return divmod_hint(p * q, md, mdri)[1];
});
}
template<typename poly>
auto powmod(poly const& p, int64_t k, poly const& md) {
int d = md.deg();
if(p == poly::xk(1) && false) { // does it actually speed anything up?..
if(k < md.deg()) {
return poly::xk(k);
} else {
auto mdr = md.reversed();
return (mdr.inv(k - md.deg() + 1, md.deg()) * mdr).reversed(md.deg());
}
}
if(md == poly::xk(d)) {
return p.pow(k, d);
}
if(md == poly::xk(d) - poly(1)) {
return p.powmod_circular(k, d);
}
return powmod_hint(p, k, md, md.reversed().inv(md.deg() + 1));
}
template<typename poly>
poly& inv_inplace(poly& q, int64_t k, size_t n) {
using poly_t = std::decay_t<poly>;
using base = poly_t::base;
if(k <= std::max<int64_t>(n, size(q.a))) {
return q.inv_inplace(k + n).div_xk_inplace(k);
}
if(k % 2) {
return inv_inplace(q, k - 1, n + 1).div_xk_inplace(1);
}
auto [q0, q1] = q.bisect();
auto qq = q0 * q0 - (q1 * q1).mul_xk_inplace(1);
inv_inplace(qq, k / 2 - q.deg() / 2, (n + 1) / 2 + q.deg() / 2);
int N = fft::com_size(size(q0.a), size(qq.a));
auto q0f = fft::dft<base>(q0.a, N);
auto q1f = fft::dft<base>(q1.a, N);
auto qqf = fft::dft<base>(qq.a, N);
int M = q0.deg() + (n + 1) / 2;
std::vector<base> A(M), B(M);
q0f.mul(qqf, A, M);
q1f.mul_inplace(qqf, B, M);
q.a.resize(n + 1);
for(size_t i = 0; i < n; i += 2) {
q.a[i] = A[q0.deg() + i / 2];
q.a[i + 1] = -B[q0.deg() + i / 2];
}
q.a.pop_back();
q.normalize();
return q;
}
template<typename poly>
poly& inv_inplace(poly& p, size_t n) {
using poly_t = std::decay_t<poly>;
using base = poly_t::base;
if(n == 1) {
return p = base(1) / p[0];
}
// Q(-x) = P0(x^2) + xP1(x^2)
auto [q0, q1] = p.bisect(n);
int N = fft::com_size(size(q0.a), (n + 1) / 2);
auto q0f = fft::dft<base>(q0.a, N);
auto q1f = fft::dft<base>(q1.a, N);
// Q(x)*Q(-x) = Q0(x^2)^2 - x^2 Q1(x^2)^2
auto qq = poly_t(q0f * q0f) - poly_t(q1f * q1f).mul_xk_inplace(1);
inv_inplace(qq, (n + 1) / 2);
auto qqf = fft::dft<base>(qq.a, N);
std::vector<base> A((n + 1) / 2), B((n + 1) / 2);
q0f.mul(qqf, A, (n + 1) / 2);
q1f.mul_inplace(qqf, B, (n + 1) / 2);
p.a.resize(n + 1);
for(size_t i = 0; i < n; i += 2) {
p.a[i] = A[i / 2];
p.a[i + 1] = -B[i / 2];
}
p.a.pop_back();
p.normalize();
return p;
}
}
#line 1 "cp-algorithms-aux/cp-algo/math/combinatorics.hpp"
#line 5 "cp-algorithms-aux/cp-algo/math/combinatorics.hpp"
namespace cp_algo::math {
// fact/rfact/small_inv are caching
// Beware of usage with dynamic mod
template<typename T>
T fact(int n) {
static std::vector<T> F(maxn);
static bool init = false;
if(!init) {
F[0] = T(1);
for(int i = 1; i < maxn; i++) {
F[i] = F[i - 1] * T(i);
}
init = true;
}
return F[n];
}
// Only works for modint types
template<typename T>
T rfact(int n) {
static std::vector<T> F(maxn);
static bool init = false;
if(!init) {
int t = std::min<int64_t>(T::mod(), maxn) - 1;
F[t] = T(1) / fact<T>(t);
for(int i = t - 1; i >= 0; i--) {
F[i] = F[i + 1] * T(i + 1);
}
init = true;
}
return F[n];
}
template<typename T>
T small_inv(int n) {
static std::vector<T> F(maxn);
static bool init = false;
if(!init) {
for(int i = 1; i < maxn; i++) {
F[i] = rfact<T>(i) * fact<T>(i - 1);
}
init = true;
}
return F[n];
}
template<typename T>
T binom_large(T n, int r) {
assert(r < maxn);
T ans = 1;
for(int i = 0; i < r; i++) {
ans = ans * T(n - i) * small_inv<T>(i + 1);
}
return ans;
}
template<typename T>
T binom(int n, int r) {
if(r < 0 || r > n) {
return T(0);
} else if(n >= maxn) {
return binom_large(T(n), r);
} else {
return fact<T>(n) * rfact<T>(r) * rfact<T>(n - r);
}
}
}
#line 1 "cp-algorithms-aux/cp-algo/math/number_theory.hpp"
#line 1 "cp-algorithms-aux/cp-algo/random/rng.hpp"
#include <chrono>
#include <random>
namespace cp_algo::random {
uint64_t rng() {
static std::mt19937_64 rng(
std::chrono::steady_clock::now().time_since_epoch().count()
);
return rng();
}
}
#line 10 "cp-algorithms-aux/cp-algo/math/number_theory.hpp"
namespace cp_algo::math {
std::vector<int64_t> factorize(int64_t m);
int64_t euler_phi(int64_t m) {
auto primes = factorize(m);
auto [from, to] = std::ranges::unique(primes);
primes.erase(from, to);
int64_t ans = m;
for(auto it: primes) {
ans -= ans / it;
}
return ans;
}
template<modint_type base>
int64_t period(base x) {
auto ans = euler_phi(base::mod());
base x0 = bpow(x, ans);
for(auto t: factorize(ans)) {
while(ans % t == 0 && x0 * bpow(x, ans / t) == x0) {
ans /= t;
}
}
return ans;
}
// Find min non-negative x s.t. a*b^x = c (mod m)
std::optional<uint64_t> discrete_log(int64_t b, int64_t c, uint64_t m, int64_t a = 1) {
if(std::abs(a - c) % m == 0) {
return 0;
}
if(std::gcd(a, m) != std::gcd(a * b, m)) {
auto res = discrete_log(b, c, m, a * b % m);
return res ? std::optional(*res + 1) : res;
}
// a * b^x is periodic here
using base = dynamic_modint;
return base::with_mod(m, [&]() -> std::optional<uint64_t> {
size_t sqrtmod = std::max<size_t>(1, std::sqrt(m) / 2);
std::unordered_map<int64_t, int> small;
base cur = a;
for(size_t i = 0; i < sqrtmod; i++) {
small[cur.getr()] = i;
cur *= b;
}
base step = bpow(base(b), sqrtmod);
cur = 1;
for(size_t k = 0; k < m; k += sqrtmod) {
auto it = small.find((base(c) * cur).getr());
if(it != end(small)) {
auto cand = base::with_mod(period(base(b)), [&](){
return base(it->second - k);
}).getr();
if(base(a) * bpow(base(b), cand) == base(c)) {
return cand;
} else {
return std::nullopt;
}
}
cur *= step;
}
return std::nullopt;
});
}
// https://en.wikipedia.org/wiki/Berlekamp-Rabin_algorithm
template<modint_type base>
std::optional<base> sqrt(base b) {
if(b == base(0)) {
return base(0);
} else if(bpow(b, (b.mod() - 1) / 2) != base(1)) {
return std::nullopt;
} else {
while(true) {
base z = random::rng();
if(z * z == b) {
return z;
}
lin<base> x(1, z, b); // x + z (mod x^2 - b)
x = bpow(x, (b.mod() - 1) / 2, lin<base>(0, 1, b));
if(x.a != base(0)) {
return x.a.inv();
}
}
}
}
// https://en.wikipedia.org/wiki/Miller–Rabin_primality_test
bool is_prime(uint64_t m) {
if(m == 1 || m % 2 == 0) {
return m == 2;
}
// m - 1 = 2^s * d
int s = std::countr_zero(m - 1);
auto d = (m - 1) >> s;
using base = dynamic_modint;
auto test = [&](base x) {
x = bpow(x, d);
if(std::abs(x.rem()) <= 1) {
return true;
}
for(int i = 1; i < s && x != -1; i++) {
x *= x;
}
return x == -1;
};
return base::with_mod(m, [&](){
// Works for all m < 2^64: https://miller-rabin.appspot.com
return std::ranges::all_of(std::array{
2, 325, 9375, 28178, 450775, 9780504, 1795265022
}, test);
});
}
// https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
void factorize(uint64_t m, std::vector<int64_t> &res) {
if(m % 2 == 0) {
factorize(m / 2, res);
res.push_back(2);
} else if(is_prime(m)) {
res.push_back(m);
} else if(m > 1) {
using base = dynamic_modint;
base::with_mod(m, [&]() {
base t = random::rng();
auto f = [&](auto x) {
return x * x + t;
};
base x, y;
base g = 1;
while(g == 1) {
for(int i = 0; i < 64; i++) {
x = f(x);
y = f(f(y));
if(x == y) [[unlikely]] {
t = random::rng();
x = y = 0;
} else {
base t = g * (x - y);
g = t == 0 ? g : t;
}
}
g = std::gcd(g.getr(), m);
}
factorize(g.getr(), res);
factorize(m / g.getr(), res);
});
}
}
std::vector<int64_t> factorize(int64_t m) {
std::vector<int64_t> res;
factorize(m, res);
return res;
}
int64_t primitive_root(int64_t p) {
using base = dynamic_modint;
return base::with_mod(p, [p](){
base t = 1;
while(period(t) != p - 1) {
t = random::rng();
}
return t.getr();
});
}
}
#line 16 "cp-algorithms-aux/cp-algo/math/poly.hpp"
namespace cp_algo::math {
template<typename T>
struct poly_t {
using base = T;
std::vector<T> a;
void normalize() {poly::impl::normalize(*this);}
poly_t(){}
poly_t(T a0): a{a0} {normalize();}
poly_t(std::vector<T> const& t): a(t) {normalize();}
poly_t(std::vector<T>&& t): a(std::move(t)) {normalize();}
poly_t operator -() const {return poly::impl::neg_inplace(poly_t(*this));}
poly_t& operator += (poly_t const& t) {return poly::impl::add(*this, t);}
poly_t& operator -= (poly_t const& t) {return poly::impl::sub(*this, t);}
poly_t operator + (poly_t const& t) const {return poly_t(*this) += t;}
poly_t operator - (poly_t const& t) const {return poly_t(*this) -= t;}
poly_t& mod_xk_inplace(size_t k) {
a.resize(std::min(size(a), k));
normalize();
return *this;
}
poly_t& mul_xk_inplace(size_t k) {
a.insert(begin(a), k, T(0));
normalize();
return *this;
}
poly_t& div_xk_inplace(int64_t k) {
if(k < 0) {
return mul_xk_inplace(-k);
}
a.erase(begin(a), begin(a) + std::min<size_t>(k, size(a)));
normalize();
return *this;
}
poly_t mod_xk(size_t k) const {return poly_t(*this).mod_xk_inplace(k);}
poly_t mul_xk(size_t k) const {return poly_t(*this).mul_xk_inplace(k);}
poly_t div_xk(int64_t k) const {return poly_t(*this).div_xk_inplace(k);}
poly_t substr(size_t l, size_t k) const {return poly::impl::substr(*this, l, k);}
poly_t& operator *= (const poly_t &t) {fft::mul(a, t.a); normalize(); return *this;}
poly_t operator * (const poly_t &t) const {return poly_t(*this) *= t;}
poly_t& operator /= (const poly_t &t) {return *this = divmod(t)[0];}
poly_t& operator %= (const poly_t &t) {return *this = divmod(t)[1];}
poly_t operator / (poly_t const& t) const {return poly_t(*this) /= t;}
poly_t operator % (poly_t const& t) const {return poly_t(*this) %= t;}
poly_t& operator *= (T const& x) {return *this = poly::impl::scale(*this, x);}
poly_t& operator /= (T const& x) {return *this *= x.inv();}
poly_t operator * (T const& x) const {return poly_t(*this) *= x;}
poly_t operator / (T const& x) const {return poly_t(*this) /= x;}
poly_t& reverse(size_t n) {return poly::impl::reverse(*this, n);}
poly_t& reverse() {return reverse(size(a));}
poly_t reversed(size_t n) const {return poly_t(*this).reverse(n);}
poly_t reversed() const {return poly_t(*this).reverse();}
std::array<poly_t, 2> divmod(poly_t const& b) const {
return poly::impl::divmod(*this, b);
}
// reduces A/B to A'/B' such that
// deg B' < deg A / 2
static std::pair<std::list<poly_t>, linfrac<poly_t>> half_gcd(auto &&A, auto &&B) {
return poly::impl::half_gcd(A, B);
}
// reduces A / B to gcd(A, B) / 0
static std::pair<std::list<poly_t>, linfrac<poly_t>> full_gcd(auto &&A, auto &&B) {
return poly::impl::full_gcd(A, B);
}
static poly_t gcd(poly_t &&A, poly_t &&B) {
full_gcd(A, B);
return A;
}
// Returns a (non-monic) characteristic polynomial
// of the minimum linear recurrence for the sequence
poly_t min_rec(size_t d) const {
return poly::impl::min_rec(*this, d);
}
// calculate inv to *this modulo t
std::optional<poly_t> inv_mod(poly_t const& t) const {
return poly::impl::inv_mod(*this, t);
};
poly_t negx() const { // A(x) -> A(-x)
auto res = *this;
for(int i = 1; i <= deg(); i += 2) {
res.a[i] = -res[i];
}
return res;
}
void print(int n) const {
for(int i = 0; i < n; i++) {
std::cout << (*this)[i] << ' ';
}
std::cout << "\n";
}
void print() const {
print(deg() + 1);
}
T eval(T x) const { // evaluates in single point x
T res(0);
for(int i = deg(); i >= 0; i--) {
res *= x;
res += a[i];
}
return res;
}
T lead() const { // leading coefficient
assert(!is_zero());
return a.back();
}
int deg() const { // degree, -1 for P(x) = 0
return (int)a.size() - 1;
}
bool is_zero() const {
return a.empty();
}
T operator [](int idx) const {
return idx < 0 || idx > deg() ? T(0) : a[idx];
}
T& coef(size_t idx) { // mutable reference at coefficient
return a[idx];
}
bool operator == (const poly_t &t) const {return a == t.a;}
bool operator != (const poly_t &t) const {return a != t.a;}
poly_t& deriv_inplace(int k = 1) {
if(deg() + 1 < k) {
return *this = poly_t{};
}
for(int i = k; i <= deg(); i++) {
a[i - k] = fact<T>(i) * rfact<T>(i - k) * a[i];
}
a.resize(deg() + 1 - k);
return *this;
}
poly_t deriv(int k = 1) const { // calculate derivative
return poly_t(*this).deriv_inplace(k);
}
poly_t& integr_inplace() {
a.push_back(0);
for(int i = deg() - 1; i >= 0; i--) {
a[i + 1] = a[i] * small_inv<T>(i + 1);
}
a[0] = 0;
return *this;
}
poly_t integr() const { // calculate integral with C = 0
std::vector<T> res(deg() + 2);
for(int i = 0; i <= deg(); i++) {
res[i + 1] = a[i] * small_inv<T>(i + 1);
}
return res;
}
size_t trailing_xk() const { // Let p(x) = x^k * t(x), return k
if(is_zero()) {
return -1;
}
int res = 0;
while(a[res] == T(0)) {
res++;
}
return res;
}
// calculate log p(x) mod x^n
poly_t& log_inplace(size_t n) {
assert(a[0] == T(1));
mod_xk_inplace(n);
return (inv_inplace(n) *= mod_xk_inplace(n).deriv()).mod_xk_inplace(n - 1).integr_inplace();
}
poly_t log(size_t n) const {
return poly_t(*this).log_inplace(n);
}
poly_t& mul_truncate(poly_t const& t, size_t k) {
fft::mul_truncate(a, t.a, k);
normalize();
return *this;
}
poly_t& exp_inplace(size_t n) {
if(is_zero()) {
return *this = T(1);
}
assert(a[0] == T(0));
a[0] = 1;
size_t a = 1;
while(a < n) {
poly_t C = log(2 * a).div_xk_inplace(a) - substr(a, 2 * a);
*this -= C.mul_truncate(*this, a).mul_xk_inplace(a);
a *= 2;
}
return mod_xk_inplace(n);
}
poly_t exp(size_t n) const { // calculate exp p(x) mod x^n
return poly_t(*this).exp_inplace(n);
}
poly_t pow_bin(int64_t k, size_t n) const { // O(n log n log k)
if(k == 0) {
return poly_t(1).mod_xk(n);
} else {
auto t = pow(k / 2, n);
t = (t * t).mod_xk(n);
return (k % 2 ? *this * t : t).mod_xk(n);
}
}
poly_t circular_closure(size_t m) const {
if(deg() == -1) {
return *this;
}
auto t = *this;
for(size_t i = t.deg(); i >= m; i--) {
t.a[i - m] += t.a[i];
}
t.a.resize(std::min(t.a.size(), m));
return t;
}
static poly_t mul_circular(poly_t const& a, poly_t const& b, size_t m) {
return (a.circular_closure(m) * b.circular_closure(m)).circular_closure(m);
}
poly_t powmod_circular(int64_t k, size_t m) const {
if(k == 0) {
return poly_t(1);
} else {
auto t = powmod_circular(k / 2, m);
t = mul_circular(t, t, m);
if(k % 2) {
t = mul_circular(t, *this, m);
}
return t;
}
}
poly_t powmod(int64_t k, poly_t const& md) const {
return poly::impl::powmod(*this, k, md);
}
// O(d * n) with the derivative trick from
// https://codeforces.com/blog/entry/73947?#comment-581173
poly_t pow_dn(int64_t k, size_t n) const {
if(n == 0) {
return poly_t(T(0));
}
assert((*this)[0] != T(0));
std::vector<T> Q(n);
Q[0] = bpow(a[0], k);
auto a0inv = a[0].inv();
for(int i = 1; i < (int)n; i++) {
for(int j = 1; j <= std::min(deg(), i); j++) {
Q[i] += a[j] * Q[i - j] * (T(k) * T(j) - T(i - j));
}
Q[i] *= small_inv<T>(i) * a0inv;
}
return Q;
}
// calculate p^k(n) mod x^n in O(n log n)
// might be quite slow due to high constant
poly_t pow(int64_t k, size_t n) const {
if(is_zero()) {
return k ? *this : poly_t(1);
}
int i = trailing_xk();
if(i > 0) {
return k >= int64_t(n + i - 1) / i ? poly_t(T(0)) : div_xk(i).pow(k, n - i * k).mul_xk(i * k);
}
if(std::min(deg(), (int)n) <= magic) {
return pow_dn(k, n);
}
if(k <= magic) {
return pow_bin(k, n);
}
T j = a[i];
poly_t t = *this / j;
return bpow(j, k) * (t.log(n) * T(k)).exp(n).mod_xk(n);
}
// returns std::nullopt if undefined
std::optional<poly_t> sqrt(size_t n) const {
if(is_zero()) {
return *this;
}
int i = trailing_xk();
if(i % 2) {
return std::nullopt;
} else if(i > 0) {
auto ans = div_xk(i).sqrt(n - i / 2);
return ans ? ans->mul_xk(i / 2) : ans;
}
auto st = math::sqrt((*this)[0]);
if(st) {
poly_t ans = *st;
size_t a = 1;
while(a < n) {
a *= 2;
ans -= (ans - mod_xk(a) * ans.inv(a)).mod_xk(a) / 2;
}
return ans.mod_xk(n);
}
return std::nullopt;
}
poly_t mulx(T a) const { // component-wise multiplication with a^k
T cur = 1;
poly_t res(*this);
for(int i = 0; i <= deg(); i++) {
res.coef(i) *= cur;
cur *= a;
}
return res;
}
poly_t mulx_sq(T a) const { // component-wise multiplication with a^{k choose 2}
T cur = 1, total = 1;
poly_t res(*this);
for(int i = 0; i <= deg(); i++) {
res.coef(i) *= total;
cur *= a;
total *= cur;
}
return res;
}
// be mindful of maxn, as the function
// requires multiplying polynomials of size deg() and n+deg()!
poly_t chirpz(T z, int n) const { // P(1), P(z), P(z^2), ..., P(z^(n-1))
if(is_zero()) {
return std::vector<T>(n, 0);
}
if(z == T(0)) {
std::vector<T> ans(n, (*this)[0]);
if(n > 0) {
ans[0] = accumulate(begin(a), end(a), T(0));
}
return ans;
}
auto A = mulx_sq(z.inv());
auto B = ones(n+deg()).mulx_sq(z);
return semicorr(B, A).mod_xk(n).mulx_sq(z.inv());
}
// res[i] = prod_{1 <= j <= i} 1/(1 - z^j)
static auto _1mzk_prod_inv(T z, int n) {
std::vector<T> res(n, 1), zk(n);
zk[0] = 1;
for(int i = 1; i < n; i++) {
zk[i] = zk[i - 1] * z;
res[i] = res[i - 1] * (T(1) - zk[i]);
}
res.back() = res.back().inv();
for(int i = n - 2; i >= 0; i--) {
res[i] = (T(1) - zk[i+1]) * res[i+1];
}
return res;
}
// prod_{0 <= j < n} (1 - z^j x)
static auto _1mzkx_prod(T z, int n) {
if(n == 1) {
return poly_t(std::vector<T>{1, -1});
} else {
auto t = _1mzkx_prod(z, n / 2);
t *= t.mulx(bpow(z, n / 2));
if(n % 2) {
t *= poly_t(std::vector<T>{1, -bpow(z, n - 1)});
}
return t;
}
}
poly_t chirpz_inverse(T z, int n) const { // P(1), P(z), P(z^2), ..., P(z^(n-1))
if(is_zero()) {
return {};
}
if(z == T(0)) {
if(n == 1) {
return *this;
} else {
return std::vector{(*this)[1], (*this)[0] - (*this)[1]};
}
}
std::vector<T> y(n);
for(int i = 0; i < n; i++) {
y[i] = (*this)[i];
}
auto prods_pos = _1mzk_prod_inv(z, n);
auto prods_neg = _1mzk_prod_inv(z.inv(), n);
T zn = bpow(z, n-1).inv();
T znk = 1;
for(int i = 0; i < n; i++) {
y[i] *= znk * prods_neg[i] * prods_pos[(n - 1) - i];
znk *= zn;
}
poly_t p_over_q = poly_t(y).chirpz(z, n);
poly_t q = _1mzkx_prod(z, n);
return (p_over_q * q).mod_xk_inplace(n).reverse(n);
}
static poly_t build(std::vector<poly_t> &res, int v, auto L, auto R) { // builds evaluation tree for (x-a1)(x-a2)...(x-an)
if(R - L == 1) {
return res[v] = std::vector<T>{-*L, 1};
} else {
auto M = L + (R - L) / 2;
return res[v] = build(res, 2 * v, L, M) * build(res, 2 * v + 1, M, R);
}
}
poly_t to_newton(std::vector<poly_t> &tree, int v, auto l, auto r) {
if(r - l == 1) {
return *this;
} else {
auto m = l + (r - l) / 2;
auto A = (*this % tree[2 * v]).to_newton(tree, 2 * v, l, m);
auto B = (*this / tree[2 * v]).to_newton(tree, 2 * v + 1, m, r);
return A + B.mul_xk(m - l);
}
}
poly_t to_newton(std::vector<T> p) {
if(is_zero()) {
return *this;
}
int n = p.size();
std::vector<poly_t> tree(4 * n);
build(tree, 1, begin(p), end(p));
return to_newton(tree, 1, begin(p), end(p));
}
std::vector<T> eval(std::vector<poly_t> &tree, int v, auto l, auto r) { // auxiliary evaluation function
if(r - l == 1) {
return {eval(*l)};
} else {
auto m = l + (r - l) / 2;
auto A = (*this % tree[2 * v]).eval(tree, 2 * v, l, m);
auto B = (*this % tree[2 * v + 1]).eval(tree, 2 * v + 1, m, r);
A.insert(end(A), begin(B), end(B));
return A;
}
}
std::vector<T> eval(std::vector<T> x) { // evaluate polynomial in (x1, ..., xn)
int n = x.size();
if(is_zero()) {
return std::vector<T>(n, T(0));
}
std::vector<poly_t> tree(4 * n);
build(tree, 1, begin(x), end(x));
return eval(tree, 1, begin(x), end(x));
}
poly_t inter(std::vector<poly_t> &tree, int v, auto ly, auto ry) { // auxiliary interpolation function
if(ry - ly == 1) {
return {*ly / a[0]};
} else {
auto my = ly + (ry - ly) / 2;
auto A = (*this % tree[2 * v]).inter(tree, 2 * v, ly, my);
auto B = (*this % tree[2 * v + 1]).inter(tree, 2 * v + 1, my, ry);
return A * tree[2 * v + 1] + B * tree[2 * v];
}
}
static auto inter(std::vector<T> x, std::vector<T> y) { // interpolates minimum polynomial from (xi, yi) pairs
int n = x.size();
std::vector<poly_t> tree(4 * n);
return build(tree, 1, begin(x), end(x)).deriv().inter(tree, 1, begin(y), end(y));
}
static auto resultant(poly_t a, poly_t b) { // computes resultant of a and b
if(b.is_zero()) {
return 0;
} else if(b.deg() == 0) {
return bpow(b.lead(), a.deg());
} else {
int pw = a.deg();
a %= b;
pw -= a.deg();
auto mul = bpow(b.lead(), pw) * T((b.deg() & a.deg() & 1) ? -1 : 1);
auto ans = resultant(b, a);
return ans * mul;
}
}
static poly_t xk(size_t n) { // P(x) = x^n
return poly_t(T(1)).mul_xk(n);
}
static poly_t ones(size_t n) { // P(x) = 1 + x + ... + x^{n-1}
return std::vector<T>(n, 1);
}
static poly_t expx(size_t n) { // P(x) = e^x (mod x^n)
return ones(n).borel();
}
static poly_t log1px(size_t n) { // P(x) = log(1+x) (mod x^n)
std::vector<T> coeffs(n, 0);
for(size_t i = 1; i < n; i++) {
coeffs[i] = (i & 1 ? T(i).inv() : -T(i).inv());
}
return coeffs;
}
static poly_t log1mx(size_t n) { // P(x) = log(1-x) (mod x^n)
return -ones(n).integr();
}
// [x^k] (a corr b) = sum_{i} a{(k-m)+i}*bi
static poly_t corr(poly_t const& a, poly_t const& b) { // cross-correlation
return a * b.reversed();
}
// [x^k] (a semicorr b) = sum_i a{i+k} * b{i}
static poly_t semicorr(poly_t const& a, poly_t const& b) {
return corr(a, b).div_xk(b.deg());
}
poly_t invborel() const { // ak *= k!
auto res = *this;
for(int i = 0; i <= deg(); i++) {
res.coef(i) *= fact<T>(i);
}
return res;
}
poly_t borel() const { // ak /= k!
auto res = *this;
for(int i = 0; i <= deg(); i++) {
res.coef(i) *= rfact<T>(i);
}
return res;
}
poly_t shift(T a) const { // P(x + a)
return semicorr(invborel(), expx(deg() + 1).mulx(a)).borel();
}
poly_t x2() { // P(x) -> P(x^2)
std::vector<T> res(2 * a.size());
for(size_t i = 0; i < a.size(); i++) {
res[2 * i] = a[i];
}
return res;
}
// Return {P0, P1}, where P(x) = P0(x) + xP1(x)
std::array<poly_t, 2> bisect(size_t n) const {
n = std::min(n, size(a));
std::vector<T> res[2];
for(size_t i = 0; i < n; i++) {
res[i % 2].push_back(a[i]);
}
return {res[0], res[1]};
}
std::array<poly_t, 2> bisect() const {
return bisect(size(a));
}
// Find [x^k] P / Q
static T kth_rec_inplace(poly_t &P, poly_t &Q, int64_t k) {
while(k > Q.deg()) {
int n = Q.a.size();
auto [Q0, Q1] = Q.bisect();
auto [P0, P1] = P.bisect();
int N = fft::com_size((n + 1) / 2, (n + 1) / 2);
auto Q0f = fft::dft<T>(Q0.a, N);
auto Q1f = fft::dft<T>(Q1.a, N);
auto P0f = fft::dft<T>(P0.a, N);
auto P1f = fft::dft<T>(P1.a, N);
Q = poly_t(Q0f * Q0f) -= poly_t(Q1f * Q1f).mul_xk_inplace(1);
if(k % 2) {
P = poly_t(Q0f *= P1f) -= poly_t(Q1f *= P0f);
} else {
P = poly_t(Q0f *= P0f) -= poly_t(Q1f *= P1f).mul_xk_inplace(1);
}
k /= 2;
}
return (P *= Q.inv_inplace(Q.deg() + 1))[k];
}
static T kth_rec(poly_t const& P, poly_t const& Q, int64_t k) {
return kth_rec_inplace(poly_t(P), poly_t(Q), k);
}
// inverse series mod x^n
poly_t& inv_inplace(size_t n) {
return poly::impl::inv_inplace(*this, n);
}
poly_t inv(size_t n) const {
return poly_t(*this).inv_inplace(n);
}
// [x^k]..[x^{k+n-1}] of inv()
// supports negative k if k+n >= 0
poly_t& inv_inplace(int64_t k, size_t n) {
return poly::impl::inv_inplace(*this, k, n);
}
poly_t inv(int64_t k, size_t n) const {
return poly_t(*this).inv_inplace(k, n);;
}
// compute A(B(x)) mod x^n in O(n^2)
static poly_t compose(poly_t A, poly_t B, int n) {
int q = std::sqrt(n);
std::vector<poly_t> Bk(q);
auto Bq = B.pow(q, n);
Bk[0] = poly_t(T(1));
for(int i = 1; i < q; i++) {
Bk[i] = (Bk[i - 1] * B).mod_xk(n);
}
poly_t Bqk(1);
poly_t ans;
for(int i = 0; i <= n / q; i++) {
poly_t cur;
for(int j = 0; j < q; j++) {
cur += Bk[j] * A[i * q + j];
}
ans += (Bqk * cur).mod_xk(n);
Bqk = (Bqk * Bq).mod_xk(n);
}
return ans;
}
// compute A(B(x)) mod x^n in O(sqrt(pqn log^3 n))
// preferrable when p = deg A and q = deg B
// are much less than n
static poly_t compose_large(poly_t A, poly_t B, int n) {
if(B[0] != T(0)) {
return compose_large(A.shift(B[0]), B - B[0], n);
}
int q = std::sqrt(n);
auto [B0, B1] = std::make_pair(B.mod_xk(q), B.div_xk(q));
B0 = B0.div_xk(1);
std::vector<poly_t> pw(A.deg() + 1);
auto getpow = [&](int k) {
return pw[k].is_zero() ? pw[k] = B0.pow(k, n - k) : pw[k];
};
std::function<poly_t(poly_t const&, int, int)> compose_dac = [&getpow, &compose_dac](poly_t const& f, int m, int N) {
if(f.deg() <= 0) {
return f;
}
int k = m / 2;
auto [f0, f1] = std::make_pair(f.mod_xk(k), f.div_xk(k));
auto [A, B] = std::make_pair(compose_dac(f0, k, N), compose_dac(f1, m - k, N - k));
return (A + (B.mod_xk(N - k) * getpow(k).mod_xk(N - k)).mul_xk(k)).mod_xk(N);
};
int r = n / q;
auto Ar = A.deriv(r);
auto AB0 = compose_dac(Ar, Ar.deg() + 1, n);
auto Bd = B0.mul_xk(1).deriv();
poly_t ans = T(0);
std::vector<poly_t> B1p(r + 1);
B1p[0] = poly_t(T(1));
for(int i = 1; i <= r; i++) {
B1p[i] = (B1p[i - 1] * B1.mod_xk(n - i * q)).mod_xk(n - i * q);
}
while(r >= 0) {
ans += (AB0.mod_xk(n - r * q) * rfact<T>(r) * B1p[r]).mul_xk(r * q).mod_xk(n);
r--;
if(r >= 0) {
AB0 = ((AB0 * Bd).integr() + A[r] * fact<T>(r)).mod_xk(n);
}
}
return ans;
}
};
template<typename base>
static auto operator * (const auto& a, const poly_t<base>& b) {
return b * a;
}
};
#line 1 "cp-algorithms-aux/cp-algo/linalg/matrix.hpp"
#line 1 "cp-algorithms-aux/cp-algo/linalg/vector.hpp"
#line 7 "cp-algorithms-aux/cp-algo/linalg/vector.hpp"
#include <valarray>
#line 9 "cp-algorithms-aux/cp-algo/linalg/vector.hpp"
#include <iterator>
#line 11 "cp-algorithms-aux/cp-algo/linalg/vector.hpp"
namespace cp_algo::linalg {
template<class vec, typename base>
struct valarray_base: std::valarray<base> {
using Base = std::valarray<base>;
using Base::Base;
valarray_base(base const& t): Base(t, 1) {}
auto begin() {return std::begin(to_valarray());}
auto begin() const {return std::begin(to_valarray());}
auto end() {return std::end(to_valarray());}
auto end() const {return std::end(to_valarray());}
bool operator == (vec const& t) const {return std::ranges::equal(*this, t);}
bool operator != (vec const& t) const {return !(*this == t);}
vec operator-() const {return Base::operator-();}
static vec from_range(auto const& R) {
vec res(std::ranges::distance(R));
std::ranges::copy(R, res.begin());
return res;
}
Base& to_valarray() {return static_cast<Base&>(*this);}
Base const& to_valarray() const {return static_cast<Base const&>(*this);}
};
template<class vec, typename base>
vec operator+(valarray_base<vec, base> const& a, valarray_base<vec, base> const& b) {
return a.to_valarray() + b.to_valarray();
}
template<class vec, typename base>
vec operator-(valarray_base<vec, base> const& a, valarray_base<vec, base> const& b) {
return a.to_valarray() - b.to_valarray();
}
template<class vec, typename base>
struct vec_base: valarray_base<vec, base> {
using Base = valarray_base<vec, base>;
using Base::Base;
static vec ei(size_t n, size_t i) {
vec res(n);
res[i] = 1;
return res;
}
virtual void add_scaled(vec const& b, base scale, size_t i = 0) {
if(scale != base(0)) {
for(; i < size(*this); i++) {
(*this)[i] += scale * b[i];
}
}
}
virtual vec const& normalize() {
return static_cast<vec&>(*this);
}
virtual base normalize(size_t i) {
return (*this)[i];
}
void read() {
for(auto &it: *this) {
std::cin >> it;
}
}
void print() const {
std::ranges::copy(*this, std::ostream_iterator<base>(std::cout, " "));
std::cout << "\n";
}
static vec random(size_t n) {
vec res(n);
std::ranges::generate(res, random::rng);
return res;
}
// Concatenate vectors
vec operator |(vec const& t) const {
vec res(size(*this) + size(t));
res[std::slice(0, size(*this), 1)] = *this;
res[std::slice(size(*this), size(t), 1)] = t;
return res;
}
// Generally, vec shouldn't be modified
// after its pivot index is set
std::pair<size_t, base> find_pivot() {
if(pivot == size_t(-1)) {
pivot = 0;
while(pivot < size(*this) && normalize(pivot) == base(0)) {
pivot++;
}
if(pivot < size(*this)) {
pivot_inv = base(1) / (*this)[pivot];
}
}
return {pivot, pivot_inv};
}
void reduce_by(vec &t) {
auto [pivot, pinv] = t.find_pivot();
if(pivot < size(*this)) {
add_scaled(t, -normalize(pivot) * pinv, pivot);
}
}
private:
size_t pivot = -1;
base pivot_inv;
};
template<typename base>
struct vec: vec_base<vec<base>, base> {
using Base = vec_base<vec<base>, base>;
using Base::Base;
};
template<math::modint_type base>
struct vec<base>: vec_base<vec<base>, base> {
using Base = vec_base<vec<base>, base>;
using Base::Base;
void add_scaled(vec const& b, base scale, size_t i = 0) override {
if(scale != base(0)) {
for(; i < size(*this); i++) {
(*this)[i].add_unsafe(scale.getr() * b[i].getr());
}
if(++counter == 8) {
for(auto &it: *this) {
it.pseudonormalize();
}
counter = 0;
}
}
}
vec const& normalize() override {
for(auto &it: *this) {
it.normalize();
}
return *this;
}
base normalize(size_t i) override {
return (*this)[i].normalize();
}
private:
size_t counter = 0;
};
}
#line 10 "cp-algorithms-aux/cp-algo/linalg/matrix.hpp"
#include <array>
namespace cp_algo::linalg {
enum gauss_mode {normal, reverse};
template<typename base_t>
struct matrix: valarray_base<matrix<base_t>, vec<base_t>> {
using base = base_t;
using Base = valarray_base<matrix<base>, vec<base>>;
using Base::Base;
matrix(size_t n): Base(vec<base>(n), n) {}
matrix(size_t n, size_t m): Base(vec<base>(m), n) {}
size_t n() const {return size(*this);}
size_t m() const {return n() ? size(row(0)) : 0;}
auto dim() const {return std::array{n(), m()};}
auto& row(size_t i) {return (*this)[i];}
auto const& row(size_t i) const {return (*this)[i];}
matrix& operator *=(base t) {for(auto &it: *this) it *= t; return *this;}
matrix operator *(base t) const {return matrix(*this) *= t;}
// Make sure the result is matrix, not Base
matrix& operator*=(matrix const& t) {return *this = *this * t;}
void read() {
for(auto &it: *this) {
it.read();
}
}
void print() const {
for(auto const& it: *this) {
it.print();
}
}
static matrix block_diagonal(std::vector<matrix> const& blocks) {
size_t n = 0;
for(auto &it: blocks) {
assert(it.n() == it.m());
n += it.n();
}
matrix res(n);
n = 0;
for(auto &it: blocks) {
for(size_t i = 0; i < it.n(); i++) {
res[n + i][std::slice(n, it.n(), 1)] = it[i];
}
n += it.n();
}
return res;
}
static matrix random(size_t n, size_t m) {
matrix res(n, m);
std::ranges::generate(res, std::bind(vec<base>::random, m));
return res;
}
static matrix random(size_t n) {
return random(n, n);
}
static matrix eye(size_t n) {
matrix res(n);
for(size_t i = 0; i < n; i++) {
res[i][i] = 1;
}
return res;
}
// Concatenate matrices
matrix operator |(matrix const& b) const {
assert(n() == b.n());
matrix res(n(), m()+b.m());
for(size_t i = 0; i < n(); i++) {
res[i] = row(i) | b[i];
}
return res;
}
matrix submatrix(auto slicex, auto slicey) const {
matrix res = (*this)[slicex];
for(auto &row: res) {
row = vec<base>(row[slicey]);
}
return res;
}
matrix T() const {
matrix res(m(), n());
for(size_t i = 0; i < n(); i++) {
for(size_t j = 0; j < m(); j++) {
res[j][i] = row(i)[j];
}
}
return res;
}
matrix operator *(matrix const& b) const {
assert(m() == b.n());
matrix res(n(), b.m());
for(size_t i = 0; i < n(); i++) {
for(size_t j = 0; j < m(); j++) {
res[i].add_scaled(b[j], row(i)[j]);
}
}
return res.normalize();
}
vec<base> apply(vec<base> const& x) const {
return (matrix(x) * *this)[0];
}
matrix pow(uint64_t k) const {
assert(n() == m());
return bpow(*this, k, eye(n()));
}
matrix& normalize() {
for(auto &it: *this) {
it.normalize();
}
return *this;
}
template<gauss_mode mode = normal>
void eliminate(size_t i, size_t k) {
auto kinv = base(1) / row(i).normalize()[k];
for(size_t j = (mode == normal) * i; j < n(); j++) {
if(j != i) {
row(j).add_scaled(row(i), -row(j).normalize(k) * kinv);
}
}
}
template<gauss_mode mode = normal>
void eliminate(size_t i) {
row(i).normalize();
for(size_t j = (mode == normal) * i; j < n(); j++) {
if(j != i) {
row(j).reduce_by(row(i));
}
}
}
template<gauss_mode mode = normal>
matrix& gauss() {
for(size_t i = 0; i < n(); i++) {
eliminate<mode>(i);
}
return normalize();
}
template<gauss_mode mode = normal>
auto echelonize(size_t lim) {
return gauss<mode>().sort_classify(lim);
}
template<gauss_mode mode = normal>
auto echelonize() {
return echelonize<mode>(m());
}
size_t rank() const {
if(n() > m()) {
return T().rank();
}
return size(matrix(*this).echelonize()[0]);
}
base det() const {
assert(n() == m());
matrix b = *this;
b.echelonize();
base res = 1;
for(size_t i = 0; i < n(); i++) {
res *= b[i][i];
}
return res;
}
std::optional<matrix> inv() const {
assert(n() == m());
matrix b = *this | eye(n());
if(size(b.echelonize<reverse>(n())[0]) < n()) {
return std::nullopt;
}
for(size_t i = 0; i < n(); i++) {
b[i] *= base(1) / b[i][i];
}
return b.submatrix(std::slice(0, n(), 1), std::slice(n(), n(), 1));
}
// Can also just run gauss on T() | eye(m)
// but it would be slower :(
auto kernel() const {
auto A = *this;
auto [pivots, free] = A.template echelonize<reverse>();
matrix sols(size(free), m());
for(size_t j = 0; j < size(pivots); j++) {
base scale = base(1) / A[j][pivots[j]];
for(size_t i = 0; i < size(free); i++) {
sols[i][pivots[j]] = A[j][free[i]] * scale;
}
}
for(size_t i = 0; i < size(free); i++) {
sols[i][free[i]] = -1;
}
return sols;
}
// [solution, basis], transposed
std::optional<std::array<matrix, 2>> solve(matrix t) const {
matrix sols = (*this | t).kernel();
if(sols.n() < t.m() || sols.submatrix(
std::slice(sols.n() - t.m(), t.m(), 1),
std::slice(m(), t.m(), 1)
) != -eye(t.m())) {
return std::nullopt;
} else {
return std::array{
sols.submatrix(std::slice(sols.n() - t.m(), t.m(), 1),
std::slice(0, m(), 1)),
sols.submatrix(std::slice(0, sols.n() - t.m(), 1),
std::slice(0, m(), 1))
};
}
}
private:
// To be called after a gaussian elimination run
// Sorts rows by pivots and classifies
// variables into pivots and free
auto sort_classify(size_t lim) {
size_t rk = 0;
std::vector<size_t> free, pivots;
for(size_t j = 0; j < lim; j++) {
for(size_t i = rk + 1; i < n() && row(rk)[j] == base(0); i++) {
if(row(i)[j] != base(0)) {
std::swap(row(i), row(rk));
row(rk) = -row(rk);
}
}
if(rk < n() && row(rk)[j] != base(0)) {
pivots.push_back(j);
rk++;
} else {
free.push_back(j);
}
}
return std::array{pivots, free};
}
};
}
#line 7 "cp-algorithms-aux/cp-algo/linalg/frobenius.hpp"
namespace cp_algo::linalg {
enum frobenius_mode {blocks, full};
template<frobenius_mode mode = blocks>
auto frobenius_form(auto const& A) {
using matrix = std::decay_t<decltype(A)>;
using base = matrix::base;
using polyn = math::poly_t<base>;
assert(A.n() == A.m());
size_t n = A.n();
std::vector<polyn> charps;
std::vector<vec<base>> basis, basis_init;
while(size(basis) < n) {
size_t start = size(basis);
auto generate_block = [&](auto x) {
while(true) {
vec<base> y = x | vec<base>::ei(n + 1, size(basis));
for(auto &it: basis) {
y.reduce_by(it);
}
y.normalize();
if(vec<base>(y[std::slice(0, n, 1)]) == vec<base>(n)) {
return polyn(std::vector<base>(begin(y) + n, end(y)));
} else {
basis_init.push_back(x);
basis.push_back(y);
x = A.apply(x);
}
}
};
auto full_rec = generate_block(vec<base>::random(n));
// Extra trimming to make it block-diagonal (expensive)
if constexpr (mode == full) {
if(full_rec.mod_xk(start) != polyn()) {
auto charp = full_rec.div_xk(start);
auto x = basis_init[start];
auto shift = full_rec / charp;
for(int j = 0; j < shift.deg(); j++) {
x.add_scaled(basis_init[j], shift[j]);
}
basis.resize(start);
basis_init.resize(start);
full_rec = generate_block(x.normalize());
}
}
charps.push_back(full_rec.div_xk(start));
}
// Find transform matrices while we're at it...
if constexpr (mode == full) {
for(size_t i = 0; i < size(basis); i++) {
for(size_t j = i + 1; j < size(basis); j++) {
basis[i].reduce_by(basis[j]);
}
basis[i].normalize();
basis[i] = vec<base>(
basis[i][std::slice(n, n, 1)]
) * (base(1) / basis[i][i]);
}
auto T = matrix::from_range(basis_init);
auto Tinv = matrix::from_range(basis);
return std::tuple{T, Tinv, charps};
} else {
return charps;
}
}
template<typename base>
auto with_frobenius(matrix<base> const& A, auto &&callback) {
auto [T, Tinv, charps] = frobenius_form<full>(A);
std::vector<matrix<base>> blocks;
for(auto charp: charps) {
matrix<base> block(charp.deg());
auto xk = callback(charp);
for(size_t i = 0; i < block.n(); i++) {
std::ranges::copy(xk.a, begin(block[i]));
xk = xk.mul_xk(1) % charp;
}
blocks.push_back(block);
}
auto S = matrix<base>::block_diagonal(blocks);
return Tinv * S * T;
}
template<typename base>
auto frobenius_pow(matrix<base> const& A, uint64_t k) {
return with_frobenius(A, [k](auto const& charp) {
return math::poly_t<base>::xk(1).powmod(k, charp);
});
}
};
#line 7 "cp-algorithms-aux/verify/linalg/pow_fast.test.cpp"
#include <bits/stdc++.h>
/*
using namespace std;
using namespace cp_algo::math;
using namespace cp_algo::linalg;
const int mod = 998244353;
using base = modint<mod>;
using polyn = poly_t<base>;
void solve() {
size_t n;
uint64_t k;
cin >> n >> k;
matrix<base> A(n);
A.read();
frobenius_pow(A, k).print();
}
signed main() {
//freopen("input.txt", "r", stdin);
ios::sync_with_stdio(0);
cin.tie(0);
int t = 1;
//cin >> t;
while(t--) {
solve();
}
}
*/
////////////////////////////////////////////////////////////////////////////////
template <unsigned M_> struct ModInt {
static constexpr unsigned M = M_;
unsigned x;
constexpr ModInt() : x(0U) {}
constexpr ModInt(unsigned x_) : x(x_ % M) {}
constexpr ModInt(unsigned long long x_) : x(x_ % M) {}
constexpr ModInt(int x_) : x(((x_ %= static_cast<int>(M)) < 0) ? (x_ + static_cast<int>(M)) : x_) {}
constexpr ModInt(long long x_) : x(((x_ %= static_cast<long long>(M)) < 0) ? (x_ + static_cast<long long>(M)) : x_) {}
ModInt &operator+=(const ModInt &a) { x = ((x += a.x) >= M) ? (x - M) : x; return *this; }
ModInt &operator-=(const ModInt &a) { x = ((x -= a.x) >= M) ? (x + M) : x; return *this; }
ModInt &operator*=(const ModInt &a) { x = (static_cast<unsigned long long>(x) * a.x) % M; return *this; }
ModInt &operator/=(const ModInt &a) { return (*this *= a.inv()); }
ModInt pow(long long e) const {
if (e < 0) return inv().pow(-e);
ModInt a = *this, b = 1U; for (; e; e >>= 1) { if (e & 1) b *= a; a *= a; } return b;
}
ModInt inv() const {
unsigned a = M, b = x; int y = 0, z = 1;
for (; b; ) { const unsigned q = a / b; const unsigned c = a - q * b; a = b; b = c; const int w = y - static_cast<int>(q) * z; y = z; z = w; }
assert(a == 1U); return ModInt(y);
}
ModInt operator+() const { return *this; }
ModInt operator-() const { ModInt a; a.x = x ? (M - x) : 0U; return a; }
ModInt operator+(const ModInt &a) const { return (ModInt(*this) += a); }
ModInt operator-(const ModInt &a) const { return (ModInt(*this) -= a); }
ModInt operator*(const ModInt &a) const { return (ModInt(*this) *= a); }
ModInt operator/(const ModInt &a) const { return (ModInt(*this) /= a); }
template <class T> friend ModInt operator+(T a, const ModInt &b) { return (ModInt(a) += b); }
template <class T> friend ModInt operator-(T a, const ModInt &b) { return (ModInt(a) -= b); }
template <class T> friend ModInt operator*(T a, const ModInt &b) { return (ModInt(a) *= b); }
template <class T> friend ModInt operator/(T a, const ModInt &b) { return (ModInt(a) /= b); }
explicit operator bool() const { return x; }
bool operator==(const ModInt &a) const { return (x == a.x); }
bool operator!=(const ModInt &a) const { return (x != a.x); }
friend std::ostream &operator<<(std::ostream &os, const ModInt &a) { return os << a.x; }
};
////////////////////////////////////////////////////////////////////////////////
constexpr unsigned MO = 1000000007;
using Mint = ModInt<MO>;
#ifdef LOCAL
std::mt19937_64 rng(58);
#else
std::mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count());
#endif
namespace square_matrix {
template <class T> vector<vector<T>> transpose(const vector<vector<T>> &a) {
const int n = a.size();
for (int i = 0; i < n; ++i) assert(static_cast<int>(a[i].size()) == n);
vector<vector<T>> b(n, vector<T>(n));
for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) b[j][i] = a[i][j];
return b;
}
template <class T> vector<T> mul(const vector<vector<T>> &a, const vector<T> &us) {
const int n = a.size();
assert(static_cast<int>(us.size()) == n);
vector<T> vs(n, 0);
for (int i = 0; i < n; ++i) {
assert(static_cast<int>(a[i].size()) == n);
for (int j = 0; j < n; ++j) vs[i] += a[i][j] * us[j];
}
return vs;
}
template <class T> vector<vector<T>> mul(const vector<vector<T>> &a, const vector<vector<T>> &b) {
const int n = a.size();
for (int i = 0; i < n; ++i) assert(static_cast<int>(a[i].size()) == n);
assert(static_cast<int>(b.size()) == n);
for (int j = 0; j < n; ++j) assert(static_cast<int>(b[j].size()) == n);
const auto bT = transpose(b);
vector<vector<T>> c(n, vector<T>(n, 0));
for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) for (int k = 0; k < n; ++k) {
c[i][j] += a[i][k] * bT[j][k];
}
return c;
}
} // namespace square_matrix
// fs represents f(X) = X^|fs| - \sum[0<=i<|fs|] fs[i] X^i
namespace mod_monic {
// X^e mod f(X)
template <class T> vector<T> power(long long e, const vector<T> &fs) {
assert(e >= 0);
const int deg = fs.size();
if (e == 0) {
vector<T> gs(deg, 0);
if (deg) gs[0] = 1;
return gs;
} else {
const auto gs = power(e >> 1, fs);
vector<T> hs(2 * deg - 1);
for (int i = 0; i < deg; ++i) for (int j = 0; j < deg; ++j) hs[i + j] += gs[i] * gs[j];
for (int i = deg - 1; --i >= 0; ) for (int j = 0; j < deg; ++j) hs[i + j] += fs[j] * hs[i + deg];
if (e & 1) {
hs.insert(hs.begin(), 0);
for (int j = 0; j < deg; ++j) hs[j] += fs[j] * hs[deg];
}
hs.resize(deg);
return hs;
}
}
} // namespace mod_monic
// a: coefficients to represent c by b
// b: basis consisting of added row vectors
// c: reduced basis
// invariants:
// a b = c
// c[i] = 0 or c[i][i] = 1
// c: upper triangular
template <class T> struct Basis {
int n;
vector<vector<T>> a, b, c;
Basis() {}
Basis(int n_) : n(n_), a(n, vector<T>(n, 0)), c(n, vector<T>(n, 0)) {}
inline int size() const {
return b.size();
}
// Returns true iff us extends the span.
// ps: coefficients to represent us by b
vector<T> ps;
bool add(const vector<T> &us) {
// invariant: us = vs + \sum[k] ps[k] b[k]
auto vs = us;
for (int k = 0; k < size(); ++k) ps[k] = 0;
for (int i = 0; i < n; ++i) if (vs[i]) {
if (c[i][i]) {
const T t = vs[i];
for (int k = 0; k < size(); ++k) ps[k] += t * a[i][k];
for (int j = i; j < n; ++j) vs[j] -= t * c[i][j];
} else {
const T s = vs[i].inv();
for (int k = 0; k < size(); ++k) a[i][k] = -s * ps[k];
a[i][size()] = s;
for (int j = i; j < n; ++j) c[i][j] = s * vs[j];
for (int k = 0; k < size(); ++k) ps[k] = 0;
ps.push_back(1);
b.push_back(us);
return true;
}
}
return false;
}
// (a, c) <- (b^-1, I)
void reduce() {
assert(size() == n);
for (int i = n; --i >= 0; ) for (int j = i + 1; j < n; ++j) {
for (int k = 0; k < n; ++k) a[i][k] -= c[i][j] * a[j][k];
c[i][j] = 0;
}
}
};
// Frobenius normal form
// [ pss[0][0] ]
// [ 1 pss[0][1] ]
// [ ... ... ]
// [ 1 pss[0][$-1] ]
// a = q [ ... ] q^-1
// [ pss[len-1][0] ]
// [ 1 pss[len-1][1] ]
// [ ... ... ]
// [ 1 pss[len-1][$-1] ]
// | | | |
// pt[0] pt[1] pt[len-1] pt[len]
// p[i](X) := T^|pss[i]| - \sum[k] pss[i][k] X^k
// p[i](X): min poly of K^n / <basis.b[0, pt[i])>
// p[len-1](X) | ... | p[0](X)
// q, q^-1: transpose of basis.b, basis.a
// Requires T(unsigned long long) to generate a random T.
// Needs the linear map mul(a, *) only.
// https://codeforces.com/blog/entry/124815
template <class T> struct Frobenius {
int n;
Basis<T> basis;
int len;
vector<int> pt;
vector<vector<T>> pss;
Frobenius() {}
// each try: O(n^3) time, Pr[failure] <= n / (field size), Pr[failure] < 1
explicit Frobenius(const vector<vector<T>> &a) {
n = a.size();
for (int i = 0; i < n; ++i) assert(static_cast<int>(a[i].size()) == n);
loop:
basis = Basis<T>(n);
len = 0;
pt = {0};
pss = {};
for (; basis.size() < n; ) {
vector<T> us(n);
for (int h = 0; h < n; ++h) us[h] = static_cast<unsigned long long>(rng());
auto tester = basis;
for (auto vs = us; tester.add(vs); vs = square_matrix::mul(a, vs)) {}
const int di = tester.size() - pt[len];
pss.emplace_back(tester.ps.end() - di, tester.ps.end());
for (int j = 0; j < len; ++j) {
const int dj = pt[j + 1] - pt[j];
if (dj < di) goto loop;
// destroys tester.ps[pt[j], pt[j + 1])
auto rs = tester.ps.begin() + pt[j];
for (int l = dj - di; --l >= 0; ) for (int k = 0; k < di; ++k) {
rs[l + k] += pss[len][k] * rs[l + di];
}
for (int k = 0; k < di; ++k) if (rs[k]) goto loop;
for (int l = 0; l < dj - di; ++l) for (int h = 0; h < n; ++h) {
us[h] -= rs[l + di] * basis.b[pt[j] + l][h];
}
}
for (int k = 0; k < di; ++k) {
basis.add(us);
us = square_matrix::mul(a, us);
}
++len;
pt.push_back(basis.size());
}
basis.reduce();
}
// O(n^2)
vector<vector<T>> left() const {
return square_matrix::transpose(basis.b);
}
// O(n^2)
vector<vector<T>> right() const {
return square_matrix::transpose(basis.a);
}
// O(n^3 + n^2 log(e)) (can use FFT for huge e)
vector<vector<T>> middle(long long e = 1) const {
assert(e >= 0);
vector<vector<T>> frob(n, vector<T>(n, 0));
for (int i = 0; i < len; ++i) {
const int di = pt[i + 1] - pt[i];
auto fs0 = mod_monic::power(e, pss[i]);
fs0.resize(2 * di, 0);
std::rotate(fs0.begin(), fs0.begin() + di, fs0.end());
auto fs = fs0.begin() + di;
for (int k = 0; k < di; ++k) {
for (int l = 0; l < di; ++l) frob[pt[i] + l][pt[i] + k] = fs[l];
--fs;
for (int l = 0; l < di; ++l) fs[l] += pss[i][l] * fs[di];
}
}
return frob;
}
// O(n^3 + n^2 log(e))
vector<vector<T>> pow(long long e) const {
return square_matrix::mul(left(), square_matrix::mul(middle(e), right()));
}
};
////////////////////////////////////////////////////////////////////////////////
// square matrix
using Mat = vector<vector<Mint>>;
Mint det(vector<vector<Mint>> a) {
const int n = a.size();
Mint ret = 1;
for (int h = 0; h < n; ++h) {
for (int i = h; i < n; ++i) if (a[i][h]) {
if (h != i) {
swap(a[h], a[i]);
ret = -ret;
}
break;
}
ret *= a[h][h];
if (!ret) break;
const Mint s = a[h][h].inv();
for (int j = h + 1; j < n; ++j) a[h][j] *= s;
for (int i = h + 1; i < n; ++i) {
const Mint t = a[i][h];
if (t) for (int j = h + 1; j < n; ++j) a[i][j] -= t * a[h][j];
}
}
return ret;
}
constexpr int FACTORIAL_STEP = 1'000'000;
constexpr ModInt<1000000007> FACTORIAL[] = {1,641102369,578095319,5832229,259081142,974067448,316220877,690120224,251368199,980250487,682498929,134623568,95936601,933097914,167332441,598816162,336060741,248744620,626497524,288843364,491101308,245341950,565768255,246899319,968999,586350670,638587686,881746146,19426633,850500036,76479948,268124147,842267748,886294336,485348706,463847391,544075857,898187927,798967520,82926604,723816384,156530778,721996174,299085602,323604647,172827403,398699886,530389102,294587621,813805606,67347853,497478507,196447201,722054885,228338256,407719831,762479457,746536789,811667359,778773518,27368307,438371670,59469516,5974669,766196482,606322308,86609485,889750731,340941507,371263376,625544428,788878910,808412394,996952918,585237443,1669644,361786913,480748381,595143852,837229828,199888908,526807168,579691190,145404005,459188207,534491822,439729802,840398449,899297830,235861787,888050723,656116726,736550105,440902696,85990869,884343068,56305184,973478770,168891766,804805577,927880474,876297919,934814019,676405347,567277637,112249297,44930135,39417871,47401357,108819476,281863274,60168088,692636218,432775082,14235602,770511792,400295761,697066277,421835306,220108638,661224977,261799937,168203998,802214249,544064410,935080803,583967898,211768084,751231582,972424306,623534362,335160196,243276029,554749550,60050552,797848181,395891998,172428290,159554990,887420150,970055531,250388809,487998999,856259313,82104855,232253360,513365505,244109365,1559745,695345956,261384175,849009131,323214113,747664143,444090941,659224434,80729842,570033864,664989237,827348878,195888993,576798521,457882808,731551699,212938473,509096183,827544702,678320208,677711203,289752035,66404266,555972231,195290384,97136305,349551356,785113347,83489485,66247239,52167191,307390891,547665832,143066173,350016754,917404120,296269301,996122673,23015220,602139210,748566338,187348575,109838563,574053420,105574531,304173654,542432219,34538816,325636655,437843114,630621321,26853683,933245637,616368450,238971581,511371690,557301633,911398531,848952161,958992544,925152039,914456118,724691727,636817583,238087006,946237212,910291942,114985663,492237273,450387329,834860913,763017204,368925948,475812562,740594930,45060610,806047532,464456846,172115341,75307702,116261993,562519302,268838846,173784895,243624360,61570384,481661251,938269070,95182730,91068149,115435332,495022305,136026497,506496856,710729672,113570024,366384665,564758715,270239666,277118392,79874094,702807165,112390913,730341625,103056890,677948390,339464594,167240465,108312174,839079953,479334442,271788964,135498044,277717575,591048681,811637561,353339603,889410460,839849206,192345193,736265527,316439118,217544623,788132977,618898635,183011467,380858207,996097969,898554793,335353644,54062950,611251733,419363534,965429853,160398980,151319402,990918946,607730875,450718279,173539388,648991369,970937898,500780548,780122909,39052406,276894233,460373282,651081062,461415770,358700839,643638805,560006119,668123525,686692315,673464765,957633609,199866123,563432246,841799766,385330357,504962686,954061253,128487469,685707545,299172297,717975101,577786541,318951960,773206631,306832604,204355779,573592106,30977140,450398100,363172638,258379324,472935553,93940075,587220627,776264326,793270300,291733496,522049725,579995261,335416359,142946099,472012302,559947225,332139472,499377092,464599136,164752359,309058615,86117128,580204973,563781682,954840109,624577416,895609896,888287558,836813268,926036911,386027524,184419613,724205533,403351886,715247054,716986954,830567832,383388563,68409439,6734065,189239124,68322490,943653305,405755338,811056092,179518046,825132993,343807435,985084650,868553027,148528617,160684257,882148737,591915968,701445829,529726489,302177126,974886682,241107368,798830099,940567523,11633075,325334066,346091869,115312728,473718967,218129285,878471898,180002392,699739374,917084264,856859395,435327356,808651347,421623838,105419548,59883031,322487421,79716267,715317963,429277690,398078032,316486674,384843585,940338439,937409008,940524812,947549662,833550543,593524514,996164327,987314628,697611981,636177449,274192146,418537348,925347821,952831975,893732627,1277567,358655417,141866945,581830879,987597705,347046911,775305697,125354499,951540811,247662371,343043237,568392357,997474832,209244402,380480118,149586983,392838702,309134554,990779998,263053337,325362513,780072518,551028176,990826116,989944961,155569943,596737944,711553356,268844715,451373308,379404150,462639908,961812918,654611901,382776490,41815820,843321396,675258797,845583555,934281721,741114145,275105629,666247477,325912072,526131620,252551589,432030917,554917439,818036959,754363835,795190182,909210595,278704903,719566487,628514947,424989675,321685608,50590510,832069712,198768464,702004730,99199382,707469729,747407118,302020341,497196934,5003231,726997875,382617671,296229203,183888367,703397904,552133875,732868367,350095207,26031303,863250534,216665960,561745549,352946234,784139777,733333339,503105966,459878625,803187381,16634739,180898306,68718097,985594252,404206040,749724532,97830135,611751357,31131935,662741752,864326453,864869025,167831173,559214642,718498895,91352335,608823837,473379392,385388084,152267158,681756977,46819124,313132653,56547945,442795120,796616594,256141983,152028387,636578562,385377759,553033642,491415383,919273670,996049638,326686486,160150665,141827977,540818053,693305776,593938674,186576440,688809790,565456578,749296077,519397500,551096742,696628828,775025061,370732451,164246193,915265013,457469634,923043932,912368644,777901604,464118005,637939935,956856710,490676632,453019482,462528877,502297454,798895521,100498586,699767918,849974789,811575797,438952959,606870929,907720182,179111720,48053248,508038818,811944661,752550134,401382061,848924691,764368449,34629406,529840945,435904287,26011548,208184231,446477394,206330671,366033520,131772368,185646898,648711554,472759660,523696723,271198437,25058942,859369491,817928963,330711333,724464507,437605233,701453022,626663115,281230685,510650790,596949867,295726547,303076380,465070856,272814771,538771609,48824684,951279549,939889684,564188856,48527183,201307702,484458461,861754542,326159309,181594759,668422905,286273596,965656187,44135644,359960756,936229527,407934361,267193060,456152084,459116722,124804049,262322489,920251227,816929577,483924582,151834896,167087470,490222511,903466878,361583925,368114731,339383292,388728584,218107212,249153339,909458706,322908524,202649964,92255682,573074791,15570863,94331513,744158074,196345098,334326205,9416035,98349682,882121662,769795511,231988936,888146074,137603545,582627184,407518072,919419361,909433461,986708498,310317874,373745190,263645931,256853930,876379959,702823274,147050765,308186532,175504139,180350107,797736554,606241871,384547635,273712630,586444655,682189174,666493603,946867127,819114541,502371023,261970285,825871994,126925175,701506133,314738056,341779962,561011609,815463367,46765164,49187570,188054995,957939114,64814326,933376898,329837066,338121343,765215899,869630152,978119194,632627667,975266085,435887178,282092463,129621197,758245605,827722926,201339230,918513230,322096036,547838438,985546115,852304035,593090119,689189630,555842733,567033437,469928208,212842957,117842065,404149413,155133422,663307737,208761293,206282795,717946122,488906585,414236650,280700600,962670136,534279149,214569244,375297772,811053196,922377372,289594327,219932130,211487466,701050258,398782410,863002719,27236531,217598709,375472836,810551911,178598958,247844667,676526196,812283640,863066876,857241854,113917835,624148346,726089763,564827277,826300950,478982047,439411911,454039189,633292726,48562889,802100365,671734977,945204804,508831870,398781902,897162044,644050694,892168027,828883117,277714559,713448377,624500515,590098114,808691930,514359662,895205045,715264908,628829100,484492064,919717789,513196123,748510389,403652653,574455974,77123823,172096141,819801784,581418893,15655126,15391652,875641535,203191898,264582598,880691101,907800444,986598821,340030191,264688936,369832433,785804644,842065079,423951674,663560047,696623384,496709826,161960209,331910086,541120825,951524114,841656666,162683802,629786193,190395535,269571439,832671304,76770272,341080135,421943723,494210290,751040886,317076664,672850561,72482816,493689107,135625240,100228913,684748812,639655136,906233141,929893103,277813439,814362881,562608724,406024012,885537778,10065330,60625018,983737173,60517502,551060742,804930491,823845496,727416538,946421040,678171399,842203531,175638827,894247956,538609927,885362182,946464959,116667533,749816133,241427979,871117927,281804989,163928347,563796647,640266394,774625892,59342705,256473217,674115061,918860977,322633051,753513874,393556719,304644842,767372800,161362528,754787150,627655552,677395736,799289297,846650652,816701166,687265514,787113234,358757251,701220427,607715125,245795606,600624983,10475577,728620948,759404319,36292292,491466901,22556579,114495791,647630109,586445753,482254337,718623833,763514207,66547751,953634340,351472920,308474522,494166907,634359666,172114298,865440961,364380585,921648059,965683742,260466949,117483873,962540888,237120480,620531822,193781724,213092254,107141741,602742426,793307102,756154604,236455213,362928234,14162538,753042874,778983779,25977209,49389215,698308420,859637374,49031023,713258160,737331920,923333660,804861409,83868974,682873215,217298111,883278906,176966527,954913,105359006,390019735,10430738,706334445,315103615,567473423,708233401,48160594,946149627,346966053,281329488,462880311,31503476,185438078,965785236,992656683,916291845,881482632,899946391,321900901,512634493,303338827,121000338,967284733,492741665,152233223,165393390,680128316,917041303,532702135,741626808,496442755,536841269,131384366,377329025,301196854,859917803,676511002,373451745,847645126,823495900,576368335,73146164,954958912,847549272,241289571,646654592,216046746,205951465,3258987,780882948,822439091,598245292,869544707,698611116,};
template <unsigned M> ModInt<M> factorial(long long n) {
assert(n >= 0);
if (n >= static_cast<long long>(M)) return 0;
const long long pos = n / FACTORIAL_STEP;
const long long m0 = pos * FACTORIAL_STEP;
const long long m1 = m0 + FACTORIAL_STEP;
if (m1 < static_cast<long long>(M) && n - m0 > m1 - n) {
ModInt<M> prod = 1;
for (long long i = m1; i > n; ) prod *= i--;
return FACTORIAL[pos + 1] / prod;
} else {
ModInt<M> prod = FACTORIAL[pos];
for (long long i = m0; i < n; ) prod *= ++i;
return prod;
}
}
int N, M;
vector<Mint> A;
vector<Mint> B;
Mint slow() {
Mat c(M, vector<Mint>(M));
for (int i = 0; i < M; ++i) for (int j = 0; j < M; ++j) {
c[i][j] = (abs(i - j) <= N) ? B[abs(i - j)] : 0;
}
Mint ans = det(c);
ans *= factorial<MO>(M);
return ans;
}
Mint fast() {
if (M <= 2*N) {
return slow();
}
const Mint invBN = B[N].inv();
/*
Mat c(2*N, vector<Mint>(2*N, 0));
for (int i = 0; i < 2*N; ++i) c[i][0] = -invBN * B[abs(i - (N - 1))];
for (int i = 0; i < 2*N - 1; ++i) c[i][i + 1] = 1;
const Frobenius<Mint> fc(c);
Mat d = fc.pow(M);
d.resize(N);
for (int i = 0; i < N; ++i) d[i].resize(N);
*/
Mat d(N, vector<Mint>(N));
{
using namespace cp_algo::math;
using namespace cp_algo::linalg;
using base = modint<MO>;
matrix<base> c(2*N);
for (int i = 0; i < 2*N; ++i) c[i][0] = (-invBN * B[abs(i - (N - 1))]).x;
for (int i = 0; i < 2*N - 1; ++i) c[i][i + 1] = 1;
const auto res = frobenius_pow(c, M);
for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) d[i][j] = (unsigned long long)res[i][j].getr();
}
Mint ans = det(d);
ans *= (M&N&1?-1:+1);
ans *= B[N].pow(M);
ans *= factorial<MO>(M);
return ans;
}
int main() {
for (; ~scanf("%d%d", &N, &M); ) {
A.resize(N + 1);
for (int i = 0; i <= N; ++i) {
scanf("%u", &A[i].x);
}
B.assign(N + 1, 0);
for (int i = 0; i <= N; ++i) for (int j = 0; j <= i; ++j) {
B[i - j] += A[i] * A[j];
}
cerr<<"B = "<<B<<endl;
const Mint ans = fast();
printf("%u\n", ans.x);
#ifdef LOCAL
if(M<=2000){
const Mint slw=slow();
cerr<<"slw = "<<slw<<endl;
assert(slw==ans);
}
#endif
}
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Wrong Answer
time: 2ms
memory: 5204kb
input:
9 6
output:
0
result:
wrong answer Sum of the elements is not equal to s