結果

問題 No.2440 Accuracy of Integer Division Approximate Functions
ユーザー 👑 Mizar
提出日時 2023-08-18 02:19:59
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 14 ms / 2,000 ms
コード長 1,930 bytes
コンパイル時間 988 ms
コンパイル使用メモリ 87,604 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2024-12-23 06:20:42
合計ジャッジ時間 2,260 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 20
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm> // min
#include <bit> // countl_zero
#include <cstdint> // uint64_t
#include <iostream> // cin, cout, ios
#include <utility> // swap
using u64 = uint64_t;
using u128 = unsigned __int128;

// calc sum_{i=0}^{n-1} floor((ai + b) / m) (mod 2^64)
u64 floor_sum_unsigned(u128 n, u128 m, u128 a, u128 b) {
    u64 ans = 0;
    for(;;) {
        if (a >= m) {
            ans += (u64)((n * (n - 1) >> 1) * (a / m));
            a %= m;
        }
        if (b >= m) {
            ans += (u64)(n * (b / m));
            b %= m;
        }
        u128 ymax = a * n + b;
        if (ymax < m) {
            return ans;
        }
        n = ymax / m;
        b = ymax % m;
        std::swap(a, m);
    }
}

// calc min(floor(a * 2^s / b), 2^64 - 1)
u64 div_helper(u128 a, u128 b, int s) {
    u64 ans = 0;
    for(;;) {
        int t = std::min(s, std::countl_zero((u64)(a >> 64)));
        a <<= t;
        if (ans > 0) {
            if (std::countl_zero(ans) < t) {
                return ~(u64)0;
            }
            ans <<= t;
        }
        s -= t;
        ans = (u64)(std::min((u128)ans + a / b, (u128)(~(u64)0)));
        a %= b;
        if (s == 0) {
            return ans;
        }
    }
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    int q;
    std::cin >> q;
    for (int i = 0; i < q; i++) {
        u64 n, d, m; int s;
        std::cin >> n >> d >> m >> s;
        u128 pow2s = (u128)1 << s, dm = (u128)d * (u128)m;
        if (pow2s < dm) {
            n = std::min(n, div_helper((u128)d, dm - pow2s, s));
            n -= floor_sum_unsigned(n + 1, pow2s, m, 0) - floor_sum_unsigned(n + 1, d, 1, 0);
        } else if (pow2s > dm) {
            n = std::min(n, div_helper((u128)d, pow2s - dm, s));
            n -= floor_sum_unsigned(n + 1, d, 1, 0) - floor_sum_unsigned(n + 1, pow2s, m, 0);
        }
        std::cout << n << '\n';
    }
    return 0;
}
0