解題思路
列出最少張支票的全部數量向量。
將面額由大到小排序並保留原索引,預計算後綴面額gcd。不整除剩餘金額的分支可立即排除,ceil(剩額/最大剩面額)是張數下界。
枚舉當前面額張數時,由最大可能數往下,並以後綴gcd的同餘式跳過必無解張數。找到較好總張數就清空舊答案,同張數則追加。
最後兩面額用線性不定方程:以模反元素求大面額張數的同餘類,取不超過剩額的最大解;因大面額較大,此解唯一最少張。最後映回原輸入順序並按數值字典序完整列出。
搜尋節點數V時約O(VN)次大整數操作,外加完整解排序及輸出;最壞為指數搜尋且依數值比值,無多項式效能保證。空間 O(N+MN)個大整數,M為最佳解數;不依S配置陣列。
Step-by-step animation
第四組公開範例10、50、30兌換60
步驟 1 / 3
步驟 1
示例面額10、50、30,總額60。
按降序50,30,10
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
cpp_int gc(cpp_int a, cpp_int b) {
while (b != 0) {
cpp_int r = a % b;
a = b;
b = r;
}
return a;
}
cpp_int inv(cpp_int a, cpp_int m) {
cpp_int b = m, x = 1, y = 0;
while (b != 0) {
cpp_int q = a / b, r = a - q * b;
a = b;
b = r;
r = x - q * y;
x = y;
y = r;
}
x %= m;
if (x < 0)
x += m;
return x;
}
cpp_int ceildiv(cpp_int a, cpp_int b) {
return (a + b - 1) / b;
}
int main() {
int n;
cin >> n;
vector<pair<cpp_int, int>> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i].first;
a[i].second = i;
}
cpp_int S;
cin >> S;
sort(a.rbegin(), a.rend());
vector<cpp_int> g(n + 1), counts(n);
for (int i = n - 1; i >= 0; i--)
g[i] = gc(g[i + 1], a[i].first);
cpp_int best = -1;
set<vector<cpp_int>> ans;
auto record = [&](cpp_int used) {
vector<cpp_int> v(n);
for (int j = 0; j < n; j++)
v[a[j].second] = counts[j];
if (best < 0 || used < best) {
best = used;
ans.clear();
}
if (used == best)
ans.insert(v);
};
function<void(int, cpp_int, cpp_int)> dfs = [&](int i, cpp_int rem, cpp_int used) {
if (rem == 0) {
for (int j = i; j < n; j++)
counts[j] = 0;
record(used);
return;
}
if (i == n || rem % g[i] != 0 ||
(best >= 0 && used + ceildiv(rem, a[i].first) > best))
return;
if (i == n - 1) {
if (rem % a[i].first == 0) {
counts[i] = rem / a[i].first;
record(used + counts[i]);
}
return;
}
if (i == n - 2) {
cpp_int A = a[i].first, B = a[i + 1].first, G = gc(A, B);
if (rem % G != 0)
return;
cpp_int step = B / G, q0 = 0;
if (step != 1)
q0 = (rem / G * inv((A / G) % step, step)) % step;
cpp_int top = rem / A;
if (q0 > top)
return;
cpp_int q = q0 + (top - q0) / step * step;
counts[i] = q;
counts[i + 1] = (rem - q * A) / B;
record(used + counts[i] + counts[i + 1]);
return;
}
cpp_int G = gc(a[i].first, g[i + 1]);
if (rem % G != 0)
return;
cpp_int step = g[i + 1] / G, q0 = 0;
if (step != 1)
q0 = (rem / G * inv((a[i].first / G) % step, step)) % step;
cpp_int top = rem / a[i].first;
if (q0 > top)
return;
cpp_int q = q0 + (top - q0) / step * step;
for (; q >= 0; q -= step) {
cpp_int rest = rem - q * a[i].first;
if (best >= 0 && used + q + ceildiv(rest, a[i + 1].first) > best)
break;
counts[i] = q;
dfs(i + 1, rest, used + q);
}
};
dfs(0, S, 0);
if (best < 0)
cout << 0 << '\n';
else {
cout << ans.size() << '\n' << best << '\n';
for (auto v : ans) {
for (int i = 0; i < n; i++)
cout << (i ? " " : "") << v[i];
cout << '\n';
}
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。