QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#759777#6694. Math ProblemKdlyhWA 28ms3564kbC++201.8kb2024-11-18 12:02:152024-11-18 12:02:16

Judging History

你现在查看的是最新测评结果

  • [2024-11-18 12:02:16]
  • 评测
  • 测评结果:WA
  • 用时:28ms
  • 内存:3564kb
  • [2024-11-18 12:02:15]
  • 提交

answer

#include "bits/stdc++.h"
using namespace std;
#ifdef LOCAL
#include "bits/debug.h"
#else
#define debug(...) (void)0
#endif
using i64 = int64_t;
using u64 = uint64_t;
using i128 = __int128_t;

// 先除再乘,不然没有意义,因为如果先乘再除就把乘的东西完全除掉了
// 进行 p 次乘法操作后,n 的范围是 [k^p × n, k^p × (n + 1) − 1],只要这个范围里面包括 m 的倍数即可停止乘法操作。因此乘法操作至多进行 logk m 次。
// 右边那一项推式子可以看出来

template <class T>
constexpr T power(T a, i64 b) {
    T res = 1;
    for (; b; b /= 2, a *= a) {
        if (b % 2) {
            res *= a;
        }
    }
    return res;
}

#define int i128

std::ostream &operator<<(std::ostream &os, i128 n) {
    std::string s;
    while (n) {
        s += '0' + n % 10;
        n /= 10;
    }
    std::reverse(s.begin(), s.end());
    return os << s;
}

void solve()
{
#define tests
    i64 n; i64 k, m, a, b; cin >> n >> k >> m >> a >> b;
    if (k == 1) {cout << (n == m ? 0 : -1) << "\n"; return ;}

    auto check = [&](int p, i128 n) {
        auto lo{power<i128>(k, p) * n}, hi{power<i128>(k, p) * (n + 1) - 1};
        for (const i128& trym : {(i128)(lo + m - 1) / m * m, (i128)hi / m * m}) if (trym >= lo and trym <= hi) {return true;}
        return false;
    };

    int pw{}; {
        auto now{n}; while (now > 0) {now /= k; pw += 1;} 
    }

    i128 ans{1LL * pw * b}, now{n}; for (int i = 0; i <= pw; i++, now /= k) {
        for (int p{}; ; p++) if (check(p, now)) {ans = min(ans, i * b + p * a); break ;}
    }

    cout << (i64)ans << "\n";

}

signed main()
{
    cin.tie(nullptr)->sync_with_stdio(false);
    i64 _ { 1 };
#ifdef tests
    cin >> _;
#endif
    while (_--) {solve();}
    return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 0ms
memory: 3556kb

input:

4
101 4 207 3 5
8 3 16 100 1
114 514 19 19 810
1 1 3 1 1

output:

11
2
0
-1

result:

ok 4 number(s): "11 2 0 -1"

Test #2:

score: -100
Wrong Answer
time: 28ms
memory: 3564kb

input:

100000
9 5 7 7674 78731
4 3 4 58482 93736
1 4 3 42396 22960
6 2 2 4534 73466
5 7 7 56203 19376
1 7 10 77129 84094
8 3 3 72793 89258
10 10 3 94847 42455
7 4 7 79273 90760
2 7 3 78496 99140
4 4 9 47018 14651
3 7 8 60936 4453
8 6 4 57267 6293
8 7 3 81697 99664
2 10 10 3935 30951
8 9 7 91391 70670
5 8 8...

output:

7674
0
22960
0
19376
77129
72793
84910
0
78496
29302
4453
0
81697
3935
70670
36522
21244
0
0
0
100934
30063
0
57852
31894
72016
6193
9486
2516
27536
0
7306
73625
11302
13802
41343
50014
58015
38743
65165
38963
26747
0
42044
45733
63574
69321
34196
1674
27200
8130
0
46609
53621
11696
7808
4630
10051
...

result:

wrong answer 3696th numbers differ - expected: '0', found: '-1'