結果

問題 No.3118 Increment or Multiply
ユーザー Kude
提出日時 2025-04-18 22:46:57
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 244 ms / 2,000 ms
コード長 2,028 bytes
コンパイル時間 3,300 ms
コンパイル使用メモリ 303,212 KB
実行使用メモリ 7,844 KB
最終ジャッジ日時 2025-04-18 22:47:05
合計ジャッジ時間 6,917 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
namespace {
#pragma GCC diagnostic ignored "-Wunused-function"
#include<atcoder/all>
#pragma GCC diagnostic warning "-Wunused-function"
using namespace std;
using namespace atcoder;
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
#define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--)
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
template<class T> bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; }
template<class T> bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; }
using ll = long long;
using P = pair<int,int>;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<ll>;
using VVL = vector<VL>;
using mint = modint998244353;

} int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int tt;
  cin >> tt;
  const mint inv2 = mint(2).inv();
  while (tt--) {
    ll n, a;
    cin >> n >> a;
    if (a == 1) {
      cout << (mint(n) * (n - 1) / 2).val() << endl;
      continue;
    }
    VL d;
    {
      ll tmp = n;
      while (tmp) {
        d.emplace_back(tmp % a);
        tmp /= a;
      }
    }
    int sz = d.size();
    VL acc(sz + 1);
    rep(i, sz) acc[i+1] = acc[i] + d[i];
    VL pa(sz);
    pa[0] = 1;
    rep(i, sz - 1) pa[i+1] = pa[i] * a;
    mint ans;
    rep(t, sz) rep(s, t + 1) {
      mint cnt = mint(pa[t - s]) * (t == sz - 1 ? d[t] - 1 : d[t]);
      ans += cnt * (cnt + 1) * inv2;
      ans += n % pa[t] / pa[s] * cnt;
      ans += (s + acc[s]) * cnt;
    }
    rep(s, sz) ans += s + acc[s];
    vector<mint> pa_acc(sz + 1);
    rep(i, sz) pa_acc[i+1] = pa_acc[i] + pa[i];
    pa.emplace_back(n + 1);
    rep(t, sz) if (d[t] + 1 < a) rep(s, t + 1) if (s) {
      mint cnt = mint(pa[t - s]) * (a - (d[t] + 1));
      mint s1 = (pa_acc[t - s] * (a - 1) * inv2 + (d[t]+1+a-1) * inv2 * pa[t - s] + n / pa[t+1] * pa[t-s+1]) * cnt;
      mint s2 = n / pa[s-1] * cnt;
      ans += s2 - s1;
      ans += (s-1 + acc[s-1]) * cnt;
    }
    cout << ans.val() << endl;
  }
}
0