結果

問題 No.2440 Accuracy of Integer Division Approximate Functions
ユーザー 👑 MizarMizar
提出日時 2023-09-01 14:04:21
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 15 ms / 2,000 ms
コード長 1,555 bytes
コンパイル時間 1,225 ms
コンパイル使用メモリ 94,136 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2025-01-03 06:33:35
合計ジャッジ時間 2,247 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
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;

u64 floor_sum_unsigned(u128 n, u128 m, u128 a, u128 b) {
    u64 x = 0;
    while(n > 0) {
        x += (u64)(a / m * (n * (n - 1) >> 1) + b / m * n);
        a %= m;
        b = a * n + b % m;
        n = b / m;
        b %= m;
        std::swap(a, m);
    }
    return x;
}

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) {
            ans = std::countl_zero(ans) >= t ? ans << t : -1ULL;
        }
        s -= t;
        ans = (u64)(std::min((u128)ans + a / b, (u128)(-1ULL)));
        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 t = (u128)1 << s, u = (u128)d * (u128)m;
        if(t < u) {
            n = std::min(n, div_helper(d, u - t, s));
            n -= floor_sum_unsigned(n + 1, t, m, 0) - floor_sum_unsigned(n + 1, d, 1, 0);
        } else if(t > u) {
            n = std::min(n, div_helper(d, t - u, s));
            n -= floor_sum_unsigned(n + 1, d, 1, 0) - floor_sum_unsigned(n + 1, t, m, 0);
        }
        std::cout << n << '\n';
    }
    return 0;
}
0