题解:CF2132C2 The Cunning Seller (hard version)
Solution
在交易次数最少的情况下(简单版本),方案是唯一的,可以把
在这个基础上,如果限制最多只能进行 -1。如果
Code
完整代码如下:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int n, k, num[30];
ll p[20];
int main() {
cin.tie(0) -> sync_with_stdio(0);
p[0] = 1; // 预处理3的正整数次幂
for (int i = 1; i < 20; i++) p[i] = p[i - 1] * 3;
int T;
cin >> T;
while (T--) {
cin >> n >> k;
int tmp = n, cnt = 0, res = 0;
while (tmp) num[cnt++] = tmp % 3, tmp /= 3; // 分解n
ll ans = 0;
for (int i = 0; i < cnt; i++) res += num[i]; // 计算最少次数
for (int i = 0; i < cnt; i++)
if (!i) ans += 3 * num[i];
else ans += (p[i + 1] + i * p[i - 1]) * num[i]; // 最少次数的花费
if (res > k) { // k小于最少次数
cout << "-1\n";
continue;
}
tmp = k - res;
for (int i = cnt - 1; i >= 1; i--) {
int c = min(num[i], tmp / 2);
num[i] -= c, tmp -= 2 * c, num[i - 1] += 3 * c, ans -= p[i - 1] * c; // 购买次数不超过k就按第二种方式购买
}
cout << ans << "\n";
}
return 0;
}