#ifndef HIDDEN_IN_VS // 折りたたみ用 // 警告の抑制 #define _CRT_SECURE_NO_WARNINGS // ライブラリの読み込み #include using namespace std; // 型名の短縮 using ll = long long; using ull = unsigned long long; // -2^63 ~ 2^63 = 9e18(int は -2^31 ~ 2^31 = 2e9) using pii = pair; using pll = pair; using pil = pair; using pli = pair; using vi = vector; using vvi = vector; using vvvi = vector; using vvvvi = vector; using vl = vector; using vvl = vector; using vvvl = vector; using vvvvl = vector; using vb = vector; using vvb = vector; using vvvb = vector; using vc = vector; using vvc = vector; using vvvc = vector; using vd = vector; using vvd = vector; using vvvd = vector; template using priority_queue_rev = priority_queue, greater>; using Graph = vvi; // 定数の定義 const double PI = acos(-1); int DX[4] = { 1, 0, -1, 0 }; // 4 近傍(下,右,上,左) int DY[4] = { 0, 1, 0, -1 }; int INF = 1001001001; ll INFL = 4004004003094073385LL; // (int)INFL = INF, (int)(-INFL) = -INF; // 入出力高速化 struct fast_io { fast_io() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(18); } } fastIOtmp; // 汎用マクロの定義 #define all(a) (a).begin(), (a).end() #define sz(x) ((int)(x).size()) #define lbpos(a, x) (int)distance((a).begin(), std::lower_bound(all(a), (x))) #define ubpos(a, x) (int)distance((a).begin(), std::upper_bound(all(a), (x))) #define Yes(b) {cout << ((b) ? "Yes\n" : "No\n");} #define rep(i, n) for(int i = 0, i##_len = int(n); i < i##_len; ++i) // 0 から n-1 まで昇順 #define repi(i, s, t) for(int i = int(s), i##_end = int(t); i <= i##_end; ++i) // s から t まで昇順 #define repir(i, s, t) for(int i = int(s), i##_end = int(t); i >= i##_end; --i) // s から t まで降順 #define repe(v, a) for(const auto& v : (a)) // a の全要素(変更不可能) #define repea(v, a) for(auto& v : (a)) // a の全要素(変更可能) #define repb(set, d) for(int set = 0, set##_ub = 1 << int(d); set < set##_ub; ++set) // d ビット全探索(昇順) #define repis(i, set) for(int i = lsb(set), bset##i = set; i < 32; bset##i -= 1 << i, i = lsb(bset##i)) // set の全要素(昇順) #define repp(a) sort(all(a)); for(bool a##_perm = true; a##_perm; a##_perm = next_permutation(all(a))) // a の順列全て(昇順) #define uniq(a) {sort(all(a)); (a).erase(unique(all(a)), (a).end());} // 重複除去 #define EXIT(a) {cout << (a) << endl; exit(0);} // 強制終了 #define inQ(x, y, u, l, d, r) ((u) <= (x) && (l) <= (y) && (x) < (d) && (y) < (r)) // 半開矩形内判定 // 汎用関数の定義 template inline ll powi(T n, int k) { ll v = 1; rep(i, k) v *= n; return v; } template inline bool chmax(T& M, const T& x) { if (M < x) { M = x; return true; } return false; } // 最大値を更新(更新されたら true を返す) template inline bool chmin(T& m, const T& x) { if (m > x) { m = x; return true; } return false; } // 最小値を更新(更新されたら true を返す) template inline int getb(T set, int i) { return (set >> i) & T(1); } template inline T smod(T n, T m) { n %= m; if (n < 0) n += m; return n; } // 非負mod // 演算子オーバーロード template inline istream& operator>>(istream& is, pair& p) { is >> p.first >> p.second; return is; } template inline istream& operator>>(istream& is, vector& v) { repea(x, v) is >> x; return is; } template inline vector& operator--(vector& v) { repea(x, v) --x; return v; } template inline vector& operator++(vector& v) { repea(x, v) ++x; return v; } #endif // 折りたたみ用 #if __has_include() #include using namespace atcoder; #ifdef _MSC_VER #include "localACL.hpp" #endif using mint = modint998244353; //using mint = static_modint<(int)1e9+7>; //using mint = modint; // mint::set_mod(m); using vm = vector; using vvm = vector; using vvvm = vector; using vvvvm = vector; using pim = pair; #endif #ifdef _MSC_VER // 手元環境(Visual Studio) #include "local.hpp" #else // 提出用(gcc) int mute_dump = 0; int frac_print = 0; #if __has_include() namespace atcoder { inline istream& operator>>(istream& is, mint& x) { ll x_; is >> x_; x = x_; return is; } inline ostream& operator<<(ostream& os, const mint& x) { os << x.val(); return os; } } #endif inline int popcount(int n) { return __builtin_popcount(n); } inline int popcount(ll n) { return __builtin_popcountll(n); } inline int lsb(int n) { return n != 0 ? __builtin_ctz(n) : 32; } inline int lsb(ll n) { return n != 0 ? __builtin_ctzll(n) : 64; } inline int msb(int n) { return n != 0 ? (31 - __builtin_clz(n)) : -1; } inline int msb(ll n) { return n != 0 ? (63 - __builtin_clzll(n)) : -1; } #define dump(...) #define dumpel(v) #define dump_math(v) #define input_from_file(f) #define output_to_file(f) #define Assert(b) { if (!(b)) { vc MLE(1<<30); rep(i,9)cout<() : O(1) * 0 で初期化する. * 制約:T は int, ll, __int128, boost::multiprecision::int256_t 等 * * Frac(T num) : O(1) * num で初期化する. * * Frac(T num, T dnm) : O(1) * num / dnm で初期化する(分母は自動的に正にする) * * a == b, a != b, a < b, a > b, a <= b, a >= b : O(1) * 大小比較を行う(分母が共通の場合は積はとらない) * * a + b, a - b, a * b, a / b : O(1) * 加減乗除を行う(和と差については,分母が共通の場合は積はとらない) * 一方が整数でも構わない.複合代入演算子も使用可. * * reduction() : O(log min(num, dnm)) * 自身の約分を行う. * * together(Frac& a, Frac& b) : O(log min(a.dnm, b.dnm)) * a と b を通分する. * * together(vector& as) : O(|as| log dnm) * as を通分する. * * T floor() : O(1) * 自身の floor を返す. * * T ceil() : O(1) * 自身の ceil を返す. * * Frac absolute() : O(1) * 自身の絶対値を返す. * * bool integerQ() : O(1) * 自身が整数かを返す. */ template struct Frac { // 分子,分母 T num, dnm; // コンストラクタ Frac() : num(0), dnm(1) {} Frac(T num) : num(num), dnm(1) {} Frac(T num_, T dnm_) : num(num_), dnm(dnm_) { // verify : https://atcoder.jp/contests/abc244/tasks/abc244_h Assert(dnm != 0); if (dnm < 0) { num *= -1; dnm *= -1; } } // 代入 Frac(const Frac& b) = default; Frac& operator=(const Frac& b) = default; // キャスト operator double() const { return (double)num / (double)dnm; } // 比較 bool operator==(const Frac& b) const { // 分母が等しいときはオーバーフロー防止のために掛け算はせず比較する. if (dnm == b.dnm) return num == b.num; return num * b.dnm == b.num * dnm; } bool operator!=(const Frac& b) const { return !(*this == b); } bool operator<(const Frac& b) const { // verify : https://atcoder.jp/contests/abc308/tasks/abc308_c // 分母が等しいときはオーバーフロー防止のために掛け算はせず比較する. if (dnm == b.dnm) return num < b.num; return (num * b.dnm < b.num * dnm); } bool operator>=(const Frac& b) const { return !(*this < b); } bool operator>(const Frac& b) const { return b < *this; } bool operator<=(const Frac& b) const { return !(*this > b); } // 整数との比較 bool operator==(T b) const { return num == b * dnm; } bool operator!=(T b) const { return num != b * dnm; } bool operator<(T b) const { return num < b * dnm; } bool operator>=(T b) const { return num >= b * dnm; } bool operator>(T b) const { return num > b * dnm; } bool operator<=(T b) const { return num <= b * dnm; } friend bool operator==(T a, const Frac& b) { return a * b.dnm == b.num; } friend bool operator!=(T a, const Frac& b) { return a * b.dnm != b.num; } friend bool operator<(T a, const Frac& b) { return a * b.dnm < b.num; } friend bool operator>=(T a, const Frac& b) { return a * b.dnm >= b.num; } friend bool operator>(T a, const Frac& b) { return a * b.dnm > b.num; } friend bool operator<=(T a, const Frac& b) { return a * b.dnm <= b.num; } // 四則演算 Frac& operator+=(const Frac& b) { // verify : https://www.codechef.com/problems/ARCTR // 分母が等しいときはオーバーフロー防止のために掛け算はせず加算する. if (dnm == b.dnm) num += b.num; else { num = num * b.dnm + b.num * dnm; dnm *= b.dnm; } return *this; } Frac& operator-=(const Frac& b) { // verify : https://www.codechef.com/problems/ARCTR // 分母が等しいときはオーバーフロー防止のために掛け算はせず加算する. if (dnm == b.dnm) num -= b.num; else { num = num * b.dnm - b.num * dnm; dnm *= b.dnm; } return *this; } Frac& operator*=(const Frac& b) { num *= b.num; dnm *= b.dnm; return *this; } Frac& operator/=(const Frac& b) { // verify : https://atcoder.jp/contests/abc301/tasks/abc301_g Assert(b.num != 0); num *= b.dnm; dnm *= b.num; if (dnm < 0) { num *= -1; dnm *= -1; } return *this; } Frac operator+(const Frac& b) const { Frac a = *this; return a += b; } Frac operator-(const Frac& b) const { Frac a = *this; return a -= b; } Frac operator*(const Frac& b) const { Frac a = *this; return a *= b; } Frac operator/(const Frac& b) const { Frac a = *this; return a /= b; } Frac operator+() const { return Frac(*this); } Frac operator-() const { return Frac(*this) *= Frac(-1); } // 整数との四則演算 Frac& operator+=(T c) { num += dnm * c; return *this; } Frac& operator-=(T c) { num -= dnm * c; return *this; } Frac& operator*=(T c) { num *= c; return *this; } Frac& operator/=(T c) { Assert(c != T(0)); dnm *= c; if (dnm < 0) { num *= -1; dnm *= -1; } return *this; } Frac operator+(T c) const { Frac a = *this; return a += c; } Frac operator-(T c) const { Frac a = *this; return a -= c; } Frac operator*(T c) const { Frac a = *this; return a *= c; } Frac operator/(T c) const { Frac a = *this; return a /= c; } friend Frac operator+(T c, const Frac& a) { return a + c; } friend Frac operator-(T c, const Frac& a) { return Frac(c) - a; } friend Frac operator*(T c, const Frac& a) { return a * c; } friend Frac operator/(T c, const Frac& a) { return Frac(c) / a; } // 約分を行う. void reduction() { // verify : https://atcoder.jp/contests/abc229/tasks/abc229_h auto g = gcd(num, dnm); num /= g; dnm /= g; } // a と b を通分する. friend void together(Frac& a, Frac& b) { // verify : https://atcoder.jp/contests/abc229/tasks/abc229_h T dnm = lcm(a.dnm, b.dnm); a.num *= dnm / a.dnm; a.dnm = dnm; b.num *= dnm / b.dnm; b.dnm = dnm; } // as を通分する. friend void together(vector& as) { // verify : https://yukicoder.me/problems/617 T dnm = 1; repe(a, as) dnm = lcm(dnm, a.dnm); repea(a, as) { a.num *= dnm / a.dnm; a.dnm = dnm; } } // 自身の絶対値を返す. Frac absolute() const { // verify : https://atcoder.jp/contests/abc393/tasks/abc393_g return Frac(abs(num), dnm); } // 自身の floor を返す. T floor() const { // verify : https://www.codechef.com/problems/LINEFIT?tab=statement if (num >= 0) return num / dnm; else return -((-num + dnm - 1) / dnm); } // 自身の ceil を返す. T ceil() const { // verify : https://www.codechef.com/problems/LINEFIT?tab=statement if (num >= 0) return (num + dnm - 1) / dnm; else return -((-num) / dnm); } // 自身が整数かを返す. bool integerQ() const { // verify : https://atcoder.jp/contests/ttpc2022/tasks/ttpc2022_g return num % dnm == 0; } #ifdef _MSC_VER friend ostream& operator<<(ostream& os, const Frac& a) { os << a.num << '/' << a.dnm; return os; } #endif }; // 愚直(有理数 num/dnm に対する答えを返す) mint naive_frac(ll num, ll dnm) { auto PQ = Frac(num, dnm); Frac dif_min(INF, 1), L_min, R_min; repi(Ld, 1, dnm - 1) repi(Ln, 0, Ld) { auto L = Frac(Ln, Ld); if (L >= PQ) continue; repi(Rd, 1, dnm - 1) repi(Rn, 0, Rd) { auto R = Frac(Rn, Rd); if (PQ >= R) continue; if (chmin(dif_min, R - L)) { L_min = L; R_min = R; } } } L_min.reduction(); R_min.reduction(); return L_min.num + L_min.dnm + R_min.num + R_min.dnm; } //【スターン・ブロコット木】 /* * vector to_path(T n, T d) : O(log min(n, d)) * 1/1 から n/d までのパスを,左[右] への移動を 'L'['R'] と表した上で連長圧縮して返す. * * pTT from_path(vector path) : O(|path|) * 1/1 から path に沿って移動した先の既約分数を n/d とし,組 {n, d} を返す. * * pTT lca(T n1, T d1, T n2, T d2) : O(log min(n1, d1, n2, d2)) * n1/d1 と n2/d2 との LCA を n/d とし,組 {n, d} を返す. * 備考 : n/d は n1/d1 ≦ n/d ≦ n2/d2 を満たす有理数のうち d が最小のものである. * * pTT ancestor(T n, T d, T dep) : O(log min(n, d, dep)) * n/d の祖先であって深さが dep の有理数を np/dp とし,組 {np, dp} を返す(なければ {-1, -1}) * * tTTTT range(T n, T d) : O(log min(n, d)) * n/d の子孫が属する開区間を (nl/dl, nr/dr) とし,4 つ組 {nl, dl, nr, dr} を返す. * * tTTTT bin_search(bool okQ(ll n, ll d), T v_max = INFL) : O(log v_max) * 分母分子がともに v_max 以下の有理数のうち,okQ() の true と false の境界の左右で * 最も深い位置にあるものを nl/dl < nr/dr とし,組 {nl, dl, nr, dr} を返す. * * pair, vector> best_approximation_fraction(T n, T d) : O(log min(n, d)) * n/d の正の {下側最良近似分数の列の列, 上側最良近似分数の列の列} の組を返す. * 最良近似分数の列 n0/d0, (n0+Δn)/(d0+Δd), ...(k 個)..., (n0+(k-1)Δn)/(d0+(k-1)Δd) は * 5 つ組 {n0, d0, Δn, Δd, k} > 0 で表す. * 注意 : 正の制約がなければ 0/1 が最良近似分数である可能性もある. */ namespace Stern_brocot_tree { // 1/1 から n/d までのパスを,左[右] への移動を 'L'['R'] と表した上で連長圧縮して返す. template vector> to_path(T n, T d) { // verify : https://judge.yosupo.jp/problem/stern_brocot_tree T g = gcd(n, d); n /= g; d /= g; T nl = 0, dl = 1; T nr = 1, dr = 0; T nm = 1, dm = 1; vector> path; // nm/dm < n/d なら始めは右に移動,さもなくば左に移動. int dir = (nm * d < n * dm) ? 1 : -1; while (1) { if (nm == n && dm == d) break; // 右に移動 if (dir == 1) { // k : num/dnm 以上の値になるまでの移動回数 T tmp = d * nr - dr * n; T k = (dm * n - d * nm + tmp - 1) / tmp; path.emplace_back('R', k); nm += k * nr; dm += k * dr; nl = nm - nr; dl = dm - dr; } // 左に移動 else { // k : num/dnm 以下の値になるまでの移動回数 T tmp = dl * n - d * nl; T k = (d * nm - dm * n + tmp - 1) / tmp; path.emplace_back('L', k); nm += k * nl; dm += k * dl; nr = nm - nl; dr = dm - dl; } dir *= -1; } return path; } // 1/1 から path に沿って移動した先の分数を n/d とし,組 {n, d} を返す. template pair from_path(const vector>& path) { // verify : https://judge.yosupo.jp/problem/stern_brocot_tree T nl = 0, dl = 1; T nr = 1, dr = 0; T nm = 1, dm = 1; for (auto [c, k] : path) { // 右に移動 if (c == 'R') { nm += k * nr; dm += k * dr; nl = nm - nr; dl = dm - dr; } // 左に移動 else { nm += k * nl; dm += k * dl; nr = nm - nl; dr = dm - dl; } } return { nm, dm }; } // n1/d1 と n2/d2 との LCAを n/d とし,組 {n, d} を返す. template pair lca(T n1, T d1, T n2, T d2) { // verify : https://judge.yosupo.jp/problem/stern_brocot_tree T g1 = gcd(n1, d1); n1 /= g1; d1 /= g1; T g2 = gcd(n2, d2); n2 /= g2; d2 /= g2; T nl = 0, dl = 1; T nr = 1, dr = 0; T nm = 1, dm = 1; // nm/dm < n/d なら始めは右に移動,さもなくば左に移動. int dir1 = (nm * d1 < n1 * dm) ? 1 : -1; int dir2 = (nm * d2 < n2 * dm) ? 1 : -1; if (dir1 != dir2) return { 1, 1 }; while (1) { if (nm == n1 && dm == d1) return { n1, d1 }; if (nm == n2 && dm == d2) return { n2, d2 }; // 右に移動 if (dir1 == 1) { // k : num/dnm 以上の値になるまでの移動回数 T tmp1 = d1 * nr - dr * n1; T k1 = (dm * n1 - d1 * nm + tmp1 - 1) / tmp1; T tmp2 = d2 * nr - dr * n2; T k2 = (dm * n2 - d2 * nm + tmp2 - 1) / tmp2; if (k1 < k2) return { nm + k1 * nr, dm + k1 * dr }; if (k1 > k2) return { nm + k2 * nr, dm + k2 * dr }; nm += k1 * nr; dm += k1 * dr; nl = nm - nr; dl = dm - dr; } // 左に移動 else { // k : num/dnm 以下の値になるまでの移動回数 T tmp1 = dl * n1 - d1 * nl; T k1 = (d1 * nm - dm * n1 + tmp1 - 1) / tmp1; T tmp2 = dl * n2 - d2 * nl; T k2 = (d2 * nm - dm * n2 + tmp2 - 1) / tmp2; if (k1 < k2) return { nm + k1 * nl, dm + k1 * dl }; if (k1 > k2) return { nm + k2 * nl, dm + k2 * dl }; nm += k1 * nl; dm += k1 * dl; nr = nm - nl; dr = dm - dl; } dir1 *= -1; } return { -1, -1 }; } // n/d の祖先であって深さが dep の有理数を np/dp とし,組 {np, dp} を返す. template pair ancestor(T n, T d, T dep) { // verify : https://judge.yosupo.jp/problem/stern_brocot_tree T g = gcd(n, d); n /= g; d /= g; T nl = 0, dl = 1; T nr = 1, dr = 0; T nm = 1, dm = 1; // nm/dm < n/d なら始めは右に移動,さもなくば左に移動. int dir = (nm * d < n * dm) ? 1 : -1; while (1) { if (nm == n && dm == d) break; // 右に移動 if (dir == 1) { // k : num/dnm 以上の値になるまでの移動回数 T tmp = d * nr - dr * n; T k = (dm * n - d * nm + tmp - 1) / tmp; if (k >= dep) return { nm + dep * nr, dm + dep * dr }; dep -= k; nm += k * nr; dm += k * dr; nl = nm - nr; dl = dm - dr; } // 左に移動 else { // k : num/dnm 以下の値になるまでの移動回数 T tmp = dl * n - d * nl; T k = (d * nm - dm * n + tmp - 1) / tmp; if (k >= dep) return { nm + dep * nl, dm + dep * dl }; dep -= k; nm += k * nl; dm += k * dl; nr = nm - nl; dr = dm - dl; } dir *= -1; } return { -1, -1 }; } // n/d の子孫が属する開区間を (nl/dl, nr/dr) とし,4 つ組 {nl, dl, nr, dr} を返す. template tuple range(T n, T d) { // verify : https://judge.yosupo.jp/problem/stern_brocot_tree T g = gcd(n, d); n /= g; d /= g; T nl = 0, dl = 1; T nr = 1, dr = 0; T nm = 1, dm = 1; // nm/dm < n/d なら始めは右に移動,さもなくば左に移動. int dir = (nm * d < n * dm) ? 1 : -1; while (1) { if (nm == n && dm == d) break; // 右に移動 if (dir == 1) { // k : num/dnm 以上の値になるまでの移動回数 T tmp = d * nr - dr * n; T k = (dm * n - d * nm + tmp - 1) / tmp; nm += k * nr; dm += k * dr; nl = nm - nr; dl = dm - dr; } // 左に移動 else { // k : num/dnm 以下の値になるまでの移動回数 T tmp = dl * n - d * nl; T k = (d * nm - dm * n + tmp - 1) / tmp; nm += k * nl; dm += k * dl; nr = nm - nl; dr = dm - dl; } dir *= -1; } return { nl, dl, nr, dr }; } // okQ() の true と false の境界を返す. template tuple bin_search(const FUNC& okQ, T v_max = T(INFL)) { // verify : https://atcoder.jp/contests/abc385/tasks/abc385_f T nl = 0, dl = 1; bool bl = okQ(nl, dl); T nr = 1, dr = 0; bool br = okQ(nr, dr); T nm = 1, dm = 1; bool bm = okQ(nm, dm); while (1) { // 右に移動 if (bl == bm) { // k_max : nm, dm が v_max を超えない k の最大値 T k_max = T(INFL); if (nr > 0) chmin(k_max, (v_max - nm) / nr); if (dr > 0) chmin(k_max, (v_max - dm) / dr); // k : okQ(nm/dm) が切り替わるまでの移動回数 T k_ng = 0, k_ok = 1; // k の丁度いい上限がわからないのでまず指数探索を行う. while (okQ(nm + k_ok * nr, dm + k_ok * dr) == bm) { k_ng = k_ok; k_ok *= 2; // 十分深くまで探しても T/F が切り替わらなかったら, // nm/dm の子孫は全て同じ T/F であると判断し開区間の右の境界を返す. if (k_ng > k_max) return { nm + k_max * nr, dm + k_max * dr, nr, dr }; } // 判明した k の上下界を用いて二分探索を行う. while (k_ok - k_ng > 1) { T k_mid = (k_ok + k_ng) / 2; if (okQ(nm + k_mid * nr, dm + k_mid * dr) != bm) k_ok = k_mid; else k_ng = k_mid; } if (k_ok > k_max) return { nm + k_max * nr, dm + k_max * dr, nr, dr }; bm = br; nm += k_ok * nr; dm += k_ok * dr; nl = nm - nr; dl = dm - dr; } // 左に移動 else { // k_max : nm, dm が v_max を超えない k の最大値 T k_max = T(INFL); if (nl > 0) chmin(k_max, (v_max - nm) / nl); if (dl > 0) chmin(k_max, (v_max - dm) / dl); // k : okQ(nm/dm) が切り替わるまでの移動回数 T k_ng = 0, k_ok = 1; // k の丁度いい上限がわからないのでまず指数探索を行う. while (okQ(nm + k_ok * nl, dm + k_ok * dl) == bm) { k_ng = k_ok; k_ok *= 2; // 十分深くまで探しても T/F が切り替わらなかったら, // nm/dm の子孫は全て同じ T/F であると判断し開区間の左の境界を返す. if (k_ng > k_max) return { nl, dl, nm + k_max * nl, dm + k_max * dl }; } // 判明した k の上下界を用いて二分探索を行う. while (k_ok - k_ng > 1) { T k_mid = (k_ok + k_ng) / 2; if (okQ(nm + k_mid * nl, dm + k_mid * dl) != bm) k_ok = k_mid; else k_ng = k_mid; } if (k_ok > k_max) return { nl, dl, nm + k_max * nl, dm + k_max * dl }; bm = bl; nm += k_ok * nl; dm += k_ok * dl; nr = nm - nl; dr = dm - dl; } } } // n/d の最良近似分数を全て返す. template pair>, vector>> best_approximation_fraction(T n, T d) { // verify : https://atcoder.jp/contests/abc333/tasks/abc333_g T g = gcd(n, d); n /= g; d /= g; T nl = 0, dl = 1; T nr = 1, dr = 0; T nm = 1, dm = 1; vector> fl, fr; // nm/dm < n/d なら始めは右に移動,さもなくば左に移動. int dir = (nm * d < n * dm) ? 1 : -1; while (1) { if (nm == n && dm == d) break; // 右に移動 if (dir == 1) { // k : num/dnm 以上の値になるまでの移動回数 T tmp = d * nr - dr * n; T k = (dm * n - d * nm + tmp - 1) / tmp; fl.emplace_back(nm, dm, nr, dr, k); nm += k * nr; dm += k * dr; nl = nm - nr; dl = dm - dr; } // 左に移動 else { // k : num/dnm 以下の値になるまでの移動回数 T tmp = dl * n - d * nl; T k = (d * nm - dm * n + tmp - 1) / tmp; fr.emplace_back(nm, dm, nl, dl, k); nm += k * nl; dm += k * dl; nr = nm - nl; dr = dm - dl; } dir *= -1; } return { fl, fr }; } /* okQ の定義の雛形 using T = ll; auto okQ = [&](T num, T dnm) { return true || false; }; */ }; //【ランレングス符号】O(n) /* * a[0..n) をランレングス符号化し,結果を格納したリスト cls を返す. * cls[i] = {c, l} は前から i 番目の連が l 個の文字 c からなることを表す. */ template ()[0])>> vector> run_length_encoding(const STR& a) { // verify : https://atcoder.jp/contests/abc381/tasks/abc381_c int n = sz(a); vector> cls; if (n == 0) return cls; cls.emplace_back(a[0], 1); // 今読んでいる文字の種類を記憶する. T c = a[0]; repi(i, 1, n - 1) { // 記憶している文字と同じ文字の場合 if (c == a[i]) { // 列の長さを増やす. cls.back().second++; } // 記憶している文字と異なる文字の場合 else { // 新しい文字を記憶しておく. c = a[i]; // 新たな列を追加する. cls.emplace_back(c, 1); } } return cls; } mint naive(const string& s) { auto rle = run_length_encoding(s); vector> path; for (auto [c, l] : rle) path.push_back({ "LR"[c - '0'], l }); auto [num, dnm] = Stern_brocot_tree::from_path(path); return naive_frac(num, dnm); } //【行列】 /* * Matrix(int n, int m) : O(n m) * n×m 零行列で初期化する. * * Matrix(int n) : O(n^2) * n×n 単位行列で初期化する. * * Matrix(vvT a) : O(n m) * 二次元配列 a[0..n)[0..m) の要素で初期化する. * * bool empty() : O(1) * 行列が空かを返す. * * A + B : O(n m) * n×m 行列 A, B の和を返す.+= も使用可. * * A - B : O(n m) * n×m 行列 A, B の差を返す.-= も使用可. * * c * A / A * c : O(n m) * n×m 行列 A とスカラー c のスカラー積を返す.*= も使用可. * * A * x : O(n m) * n×m 行列 A と n 次元列ベクトル x の積を返す. * * x * A : O(n m)(やや遅い) * m 次元行ベクトル x と n×m 行列 A の積を返す. * * A * B : O(n m l) * n×m 行列 A と m×l 行列 B の積を返す. * * Mat pow(ll d) : O(n^3 log d) * 自身を d 乗した行列を返す. */ template struct Matrix { int n, m; // 行列のサイズ(n 行 m 列) vector> v; // 行列の成分 // n×m 零行列で初期化する. Matrix(int n, int m) : n(n), m(m), v(n, vector(m)) {} // n×n 単位行列で初期化する. Matrix(int n) : n(n), m(n), v(n, vector(n)) { rep(i, n) v[i][i] = T(1); } // 二次元配列 a[0..n)[0..m) の要素で初期化する. Matrix(const vector>& a) : n(sz(a)), m(sz(a[0])), v(a) {} Matrix() : n(0), m(0) {} // 代入 Matrix(const Matrix&) = default; Matrix& operator=(const Matrix&) = default; // アクセス inline vector const& operator[](int i) const { return v[i]; } inline vector& operator[](int i) { // verify : https://judge.yosupo.jp/problem/matrix_product // inline を付けて [] でアクセスするとなぜか v[] への直接アクセスより速くなった. return v[i]; } // 入力 friend istream& operator>>(istream& is, Matrix& a) { rep(i, a.n) rep(j, a.m) is >> a.v[i][j]; return is; } // 行の追加 void push_back(const vector& a) { Assert(sz(a) == m); v.push_back(a); n++; } // 行の削除 void pop_back() { Assert(n > 0); v.pop_back(); n--; } // サイズ変更 void resize(int n_) { v.resize(n_); n = n_; } void resize(int n_, int m_) { n = n_; m = m_; v.resize(n); rep(i, n) v[i].resize(m); } // 空か bool empty() const { return min(n, m) == 0; } // 比較 bool operator==(const Matrix& b) const { return n == b.n && m == b.m && v == b.v; } bool operator!=(const Matrix& b) const { return !(*this == b); } // 加算,減算,スカラー倍 Matrix& operator+=(const Matrix& b) { rep(i, n) rep(j, m) v[i][j] += b[i][j]; return *this; } Matrix& operator-=(const Matrix& b) { rep(i, n) rep(j, m) v[i][j] -= b[i][j]; return *this; } Matrix& operator*=(const T& c) { rep(i, n) rep(j, m) v[i][j] *= c; return *this; } Matrix operator+(const Matrix& b) const { return Matrix(*this) += b; } Matrix operator-(const Matrix& b) const { return Matrix(*this) -= b; } Matrix operator*(const T& c) const { return Matrix(*this) *= c; } friend Matrix operator*(const T& c, const Matrix& a) { return a * c; } Matrix operator-() const { return Matrix(*this) *= T(-1); } // 行列ベクトル積 : O(m n) vector operator*(const vector& x) const { vector y(n); rep(i, n) rep(j, m) y[i] += v[i][j] * x[j]; return y; } // ベクトル行列積 : O(m n) friend vector operator*(const vector& x, const Matrix& a) { vector y(a.m); rep(i, a.n) rep(j, a.m) y[j] += x[i] * a[i][j]; return y; } // 積:O(n^3) Matrix operator*(const Matrix& b) const { // verify : https://judge.yosupo.jp/problem/matrix_product Matrix res(n, b.m); rep(i, res.n) rep(k, m) rep(j, res.m) res[i][j] += v[i][k] * b[k][j]; return res; } Matrix& operator*=(const Matrix& b) { *this = *this * b; return *this; } // 累乗:O(n^3 log d) Matrix pow(ll d) const { // verify : https://judge.yosupo.jp/problem/pow_of_matrix Matrix res(n), pow2 = *this; while (d > 0) { if (d & 1) res *= pow2; pow2 *= pow2; d >>= 1; } return res; } #ifdef _MSC_VER friend ostream& operator<<(ostream& os, const Matrix& a) { rep(i, a.n) { os << "["; rep(j, a.m) os << a[i][j] << " ]"[j == a.m - 1]; if (i < a.n - 1) os << "\n"; } return os; } #endif }; //【行簡約形(行交換なし)】O(n m min(n, m)) /* * 行基本変形(行交換なし)で n×m 行列 A を行簡約形に変形し,ピボット位置のリストを返す. */ template vector row_reduced_form(Matrix& A) { int n = A.n, m = A.m; vector piv; piv.reserve(min(n, m)); // 未確定の列を記録しておくリスト list rjs; rep(j, m) rjs.push_back(j); rep(i, n) { // 第 i 行の係数を左から走査し非 0 を見つける. auto it = rjs.begin(); for (; it != rjs.end(); it++) if (A[i][*it] != 0) break; // 第 i 行の全てが 0 なら無視する. if (it == rjs.end()) continue; // A[i][j] をピボットに選択する. int j = *it; rjs.erase(it); piv.emplace_back(i, j); // A[i][j] が 1 になるよう行全体を A[i][j] で割る. T Aij_inv = T(1) / A[i][j]; repi(j2, j, m - 1) A[i][j2] *= Aij_inv; // 第 i 行以外の第 j 列の成分が全て 0 になるよう第 i 行を定数倍して減じる. rep(i2, n) if (A[i2][j] != 0 && i2 != i) { T mul = A[i2][j]; repi(j2, j, m - 1) A[i2][j2] -= A[i][j2] * mul; } } return piv; } //【逆行列】O(n^3) /* * n 次正方行列 mat の逆行列を返す(存在しなければ空) */ template Matrix inverse_matrix(const Matrix& mat) { // verify : https://judge.yosupo.jp/problem/inverse_matrix int n = mat.n; // 元の行列 mat と単位行列を繋げた拡大行列 v を作る. vector> v(n, vector(2 * n)); rep(i, n) rep(j, n) { v[i][j] = mat[i][j]; if (i == j) v[i][n + j] = 1; } int m = 2 * n; // 注目位置を (i, j)(i 行目かつ j 列目)とする. int i = 0, j = 0; // 拡大行列に対して行基本変形を行い,左側を単位行列にすることを目指す. while (i < n && j < m) { // 同じ列の下方の行から非 0 成分を見つける. int i2 = i; while (i2 < n && v[i2][j] == T(0)) i2++; // 見つからなかったら全て 0 の列があったので mat は非正則 if (i2 == n) return Matrix(); // 見つかったら i 行目とその行を入れ替える. if (i != i2) swap(v[i], v[i2]); // v[i][j] が 1 になるよう行全体を v[i][j] で割る. T vij_inv = T(1) / v[i][j]; repi(j2, j, m - 1) v[i][j2] *= vij_inv; // v[i][j] と同じ列の成分が全て 0 になるよう i 行目を定数倍して減じる. rep(i2, n) { // i 行目だけは引かない. if (i2 == i) continue; T mul = v[i2][j]; repi(j2, j, m - 1) v[i2][j2] -= v[i][j2] * mul; } // 注目位置を右下に移す. i++; j++; } // 拡大行列の右半分が mat の逆行列なのでコピーする. Matrix mat_inv(n, n); rep(i, n) rep(j, n) mat_inv[i][j] = v[i][n + j]; return mat_inv; } // 遷移行列の係数を計算し,埋め込み用のコードを出力する. // 待てない場合は len_max とか LB_max とかを指定する. pair>, vm> embed_coefs(int COL, int len_max = INF, int LB_max = INF) { vector ss{""}; int idx = 0; vector piv_prv; repi(len, 0, INF) { dump("----------- len:", len, "--------------"); int L = sz(ss); int LB = min(L, LB_max); dump("L:", L); // (i,j) 成分が naive(ss[i] + ss[j]) であるような行列 mat を得る. Matrix mat(L, LB); rep(i, L) rep(j, LB) mat[i][j] = naive(ss[i] + ss[j]); //dump("mat:"); dump(mat); // mat に対して行基本変形を行いピボット位置のリスト piv を得る. auto piv = row_reduced_form(mat); dump("piv[0.." + to_string(sz(piv)) + "):"); dump(piv); // rank の更新がなかったら必要な情報は揃ったとみなして打ち切る. if (len == len_max || (sz(piv) > 0 && sz(piv) == sz(piv_prv))) { // たまに失敗する. int DIM = sz(piv); // 選択した行と列をそれぞれ昇順に並べて is, js とする(0 始まりのはず) vi is(DIM), js(DIM); rep(r, DIM) tie(is[r], js[r]) = piv[r]; sort(all(js)); // 基底の変換行列 P を得る. Matrix matP(DIM, DIM); rep(i, DIM) rep(j, DIM) matP[i][j] = naive(ss[is[i]] + ss[js[j]]); // P の逆行列 P_inv を得る. auto matP_inv = inverse_matrix(matP); // 各文字に対応する表現行列を得る. vector> matAs(COL, Matrix(DIM, DIM)); rep(c, COL) { char ch = '0' + c; rep(i, DIM) rep(j, DIM) matAs[c][i][j] = naive(ss[is[i]] + ch + ss[js[j]]); matAs[c] = matAs[c] * matP_inv; } // 右端を閉じるためのベクトルを得る. vm vecP(DIM); rep(i, DIM) vecP[i] = matP[i][0]; // 埋め込み用の文字列を出力する. auto to_signed_string = [](mint x) { int v = x.val(); int mod = mint::mod(); if (2 * v > mod) v -= mod; return to_string(v); }; string eb = "constexpr int DIM = "; eb += to_string(DIM); eb += ";\n"; eb += "constexpr int COL = "; eb += to_string(COL); eb += ";\n"; eb += "VTYPE matAs[COL][DIM][DIM] = {\n"; rep(c, COL) { eb += "{"; rep(i, DIM) { eb += "{"; rep(j, DIM) eb += to_signed_string(matAs[c][i][j]) + ","; eb.pop_back(); eb += "},"; } eb.pop_back(); eb += "},\n"; } eb.pop_back(); eb.pop_back(); eb += "};\n"; eb += "VTYPE vecP[DIM] = {"; rep(i, DIM) eb += to_signed_string(vecP[i]) + ","; eb.pop_back(); eb += "};\n"; cout << eb; exit(0); return { matAs, vecP }; } // 基底ガチャ //mt19937_64 mt((int)time(NULL)); shuffle(ss.begin() + idx, ss.end(), mt); // 次に長い文字列たちを ss に追加する. int nidx = sz(ss); repi(i, idx, nidx - 1) rep(c, COL) { ss.push_back(ss[i]); ss.back().push_back('0' + c); } idx = nidx; piv_prv = move(piv); } } //【正方行列(固定サイズ)】 /* * Fixed_matrix() : O(n^2) * T の要素を成分にもつ n×n 零行列で初期化する. * * Fixed_matrix(bool identity = true) : O(n^2) * T の要素を成分にもつ n×n 単位行列で初期化する. * * Fixed_matrix(vvT a) : O(n^2) * 二次元配列 a[0..n)[0..n) の要素で初期化する. * * A + B : O(n^2) * n×n 行列 A, B の和を返す.+= も使用可. * * A - B : O(n^2) * n×n 行列 A, B の差を返す.-= も使用可. * * c * A / A * c : O(n^2) * n×n 行列 A とスカラー c のスカラー積を返す.*= も使用可. * * A * x : O(n^2) * n×n 行列 A と n 次元列ベクトル array x の積を返す. * * x * A : O(n^2)(やや遅い) * n 次元行ベクトル array x と n×n 行列 A の積を返す. * * A * B : O(n^3) * n×n 行列 A と n×n 行列 B の積を返す. * * Mat pow(ll d) : O(n^3 log d) * 自身を d 乗した行列を返す. */ template struct Fixed_matrix { array, n> v; // 行列の成分 // n×n 零行列で初期化する.identity = true なら n×n 単位行列で初期化する. Fixed_matrix(bool identity = false) { rep(i, n) v[i].fill(T(0)); if (identity) rep(i, n) v[i][i] = T(1); } // 二次元配列 a[0..n)[0..n) の要素で初期化する. Fixed_matrix(const vector>& a) { // verify : https://yukicoder.me/problems/no/1000 Assert(sz(a) == n && sz(a[0]) == n); rep(i, n) rep(j, n) v[i][j] = a[i][j]; } // 代入 Fixed_matrix(const Fixed_matrix&) = default; Fixed_matrix& operator=(const Fixed_matrix&) = default; // アクセス inline array const& operator[](int i) const { return v[i]; } inline array& operator[](int i) { return v[i]; } // 入力 friend istream& operator>>(istream& is, Fixed_matrix& a) { rep(i, n) rep(j, n) is >> a[i][j]; return is; } // 比較 bool operator==(const Fixed_matrix& b) const { return v == b.v; } bool operator!=(const Fixed_matrix& b) const { return !(*this == b); } // 加算,減算,スカラー倍 Fixed_matrix& operator+=(const Fixed_matrix& b) { rep(i, n) rep(j, n) v[i][j] += b[i][j]; return *this; } Fixed_matrix& operator-=(const Fixed_matrix& b) { rep(i, n) rep(j, n) v[i][j] -= b[i][j]; return *this; } Fixed_matrix& operator*=(const T& c) { rep(i, n) rep(j, n) v[i][j] *= c; return *this; } Fixed_matrix operator+(const Fixed_matrix& b) const { return Fixed_matrix(*this) += b; } Fixed_matrix operator-(const Fixed_matrix& b) const { return Fixed_matrix(*this) -= b; } Fixed_matrix operator*(const T& c) const { return Fixed_matrix(*this) *= c; } friend Fixed_matrix operator*(const T& c, const Fixed_matrix& a) { return a * c; } Fixed_matrix operator-() const { return Fixed_matrix(*this) *= T(-1); } // 行列ベクトル積 : O(n^2) array operator*(const array& x) const { array y{ 0 }; rep(i, n) rep(j, n) y[i] += v[i][j] * x[j]; return y; } // ベクトル行列積 : O(n^2) friend array operator*(const array& x, const Fixed_matrix& a) { array y{ 0 }; rep(i, n) rep(j, n) y[j] += x[i] * a[i][j]; return y; } // 積:O(n^3) Fixed_matrix operator*(const Fixed_matrix& b) const { // verify : https://yukicoder.me/problems/no/1000 Fixed_matrix res; rep(i, n) rep(k, n) rep(j, n) res[i][j] += v[i][k] * b[k][j]; return res; } Fixed_matrix& operator*=(const Fixed_matrix& b) { *this = *this * b; return *this; } // 累乗:O(n^3 log d) Fixed_matrix pow(ll d) const { // verify : https://yukicoder.me/problems/no/2810 Fixed_matrix res(true), pow2(*this); while (d > 0) { if (d & 1) res *= pow2; pow2 *= pow2; d /= 2; } return res; } #ifdef _MSC_VER friend ostream& operator<<(ostream& os, const Fixed_matrix& a) { rep(i, n) { os << "["; rep(j, n) os << a[i][j] << " ]"[j == n - 1]; if (i < n - 1) os << "\n"; } return os; } #endif }; //【累乗(モノイド)】 /* * Pow_monoid(S x, ll N) : O(log N) * x^[0..N] まで計算できるよう初期化する. * x はモノイド (S, op, e) の元とする. * * S pow(ll n) : O(log n) * x^n を返す.繰り返し二乗法の 2 倍速い. */ template class Pow_monoid { vector pow2; int K; public: // x^[0..N] まで計算できるよう初期化する.x はモノイド (S, op, e) の元とする. Pow_monoid(S x, ll N) { // verify : https://yukicoder.me/problems/no/3343 K = msb(N) + 1; pow2.resize(K); rep(k, K) { pow2[k] = x; x = op(x, x); } } Pow_monoid() {}; // x^n を返す.繰り返し二乗法の 2 倍速い. S pow(ll n) { // verify : https://yukicoder.me/problems/no/3343 S res(e()); int k = 0; while (n > 0) { if (n & 1) res = op(res, pow2[k]); n /= 2; k++; } return res; } }; using VTYPE = ll; // --------------- embed_coefs() からの出力を貼る ---------------- constexpr int DIM = 4; constexpr int COL = 2; VTYPE matAs[COL][DIM][DIM] = { {{0,1,0,0},{0,0,0,1},{0,0,1,0},{0,-1,0,2}}, {{0,0,1,0},{0,7,0,-4},{0,0,1,0},{0,9,0,-5}} }; VTYPE vecP[DIM] = { 2,3,2,4 }; // -------------------------------------------------------------- using MAT = Fixed_matrix; MAT opMAT(MAT a, MAT b) { return a * b; } MAT eMAT() { return MAT(1); } #define MatrixMul_monoid MAT, opMAT, eMAT VTYPE solve(ll num, ll dnm) { array, COL> MatAs; rep(k, COL) rep(i, DIM) rep(j, DIM) MatAs[k][i][j] = matAs[k][i][j]; Pow_monoid powMatL(MatAs[0], (ll)1e18); Pow_monoid powMatR(MatAs[1], (ll)1e18); array dp; rep(i, DIM) dp[i] = 0; dp[0] = 1; auto path = Stern_brocot_tree::to_path(num, dnm); for (auto [c, l] : path) { if (c == 'L') { dp = dp * powMatL.pow(l); } else if (c == 'R') { dp = dp * powMatR.pow(l); } } VTYPE res = 0; rep(j, DIM) res += dp[j] * vecP[j]; return res; } int main() { // input_from_file("input.txt"); // output_to_file("output.txt"); //【方法】 // 愚直を書いて集めたデータをもとに遷移行列を復元する. //【使い方】 // 1. mint naive(文字列) を実装する. // 2. embed_coefs(文字の種類数); を実行する. // 3. 出力を solve() 内に貼る. // 4. auto dp = solve<答えの型>(文字列) で勝手に DP してくれる. dump(naive_frac(1, 1)); dump("====="); // 0 : L, 1 : R // embed_coefs(2, INF, INF); ll a, b; cin >> a >> b; dump(naive_frac(a, b)); dump("====="); auto res = solve(a, b); cout << res << "\n"; } /* ----------- len: 0 -------------- L: 1 piv[0..0): ----------- len: 1 -------------- L: 3 piv[0..2): (0,1) (1,0) ----------- len: 2 -------------- L: 7 piv[0..2): (0,1) (1,0) constexpr int DIM = 2; constexpr int COL = 2; VTYPE matAs[COL][DIM][DIM] = { {{0,1},{-1,2}}, {{0,1},{-1,2}}}; VTYPE vecP[DIM] = {0,1}; */