結果

問題 No.2440 Accuracy of Integer Division Approximate Functions
ユーザー 👑 MizarMizar
提出日時 2023-09-01 14:04:21
言語 C++23
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 13 ms / 2,000 ms
コード長 1,555 bytes
コンパイル時間 1,259 ms
コンパイル使用メモリ 87,704 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-01 14:04:24
合計ジャッジ時間 2,775 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 12 ms
4,380 KB
testcase_02 AC 11 ms
4,380 KB
testcase_03 AC 12 ms
4,380 KB
testcase_04 AC 12 ms
4,380 KB
testcase_05 AC 12 ms
4,380 KB
testcase_06 AC 11 ms
4,380 KB
testcase_07 AC 11 ms
4,384 KB
testcase_08 AC 11 ms
4,380 KB
testcase_09 AC 11 ms
4,384 KB
testcase_10 AC 11 ms
4,384 KB
testcase_11 AC 13 ms
4,380 KB
testcase_12 AC 13 ms
4,380 KB
testcase_13 AC 12 ms
4,384 KB
testcase_14 AC 12 ms
4,384 KB
testcase_15 AC 12 ms
4,380 KB
testcase_16 AC 9 ms
4,384 KB
testcase_17 AC 9 ms
4,384 KB
testcase_18 AC 9 ms
4,380 KB
testcase_19 AC 8 ms
4,384 KB
testcase_20 AC 9 ms
4,384 KB
権限があれば一括ダウンロードができます

ソースコード

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