#include <bits/stdc++.h> using namespace std; const int N = 32; int h, w; int n, d[N]; map<tuple<int, int, int>, long long> cache; long long solve(int a, int b, int i) { // cerr << "solving: " << a << ' ' << b << ' ' << i << '\n'; if (a == 0 || b == 0) return 0; assert(i >= 0); if (d[i] > a || d[i] > b) return solve(a, b, i - 1); auto key = tie(a, b, i); if (cache.count(key)) return cache[key]; int p = (a / d[i]) * d[i]; int q = (b / d[i]) * d[i]; if (p == a) return cache[key] = solve(a, b - q, i) + 1LL * (a / d[i]) * (b / d[i]); if (q == b) return cache[key] = solve(a - p, b, i) + 1LL * (a / d[i]) * (b / d[i]); return cache[key] = min(solve(a - p, b, i) + solve(p, b - q, i), solve(a - p, q, i) + solve(a, b - q, i)) + 1LL * (a / d[i]) * (b / d[i]); } int main() { ios::sync_with_stdio(false), cin.tie(nullptr); cin >> h >> w; cin >> n; for (int i = 0; i < n; i++) cin >> d[i]; if (h % d[0] != 0 || w % d[0] != 0) { cout << "-1\n"; return 0; } else { cout << solve(h, w, n - 1) << '\n'; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <bits/stdc++.h> using namespace std; const int N = 32; int h, w; int n, d[N]; map<tuple<int, int, int>, long long> cache; long long solve(int a, int b, int i) { // cerr << "solving: " << a << ' ' << b << ' ' << i << '\n'; if (a == 0 || b == 0) return 0; assert(i >= 0); if (d[i] > a || d[i] > b) return solve(a, b, i - 1); auto key = tie(a, b, i); if (cache.count(key)) return cache[key]; int p = (a / d[i]) * d[i]; int q = (b / d[i]) * d[i]; if (p == a) return cache[key] = solve(a, b - q, i) + 1LL * (a / d[i]) * (b / d[i]); if (q == b) return cache[key] = solve(a - p, b, i) + 1LL * (a / d[i]) * (b / d[i]); return cache[key] = min(solve(a - p, b, i) + solve(p, b - q, i), solve(a - p, q, i) + solve(a, b - q, i)) + 1LL * (a / d[i]) * (b / d[i]); } int main() { ios::sync_with_stdio(false), cin.tie(nullptr); cin >> h >> w; cin >> n; for (int i = 0; i < n; i++) cin >> d[i]; if (h % d[0] != 0 || w % d[0] != 0) { cout << "-1\n"; return 0; } else { cout << solve(h, w, n - 1) << '\n'; } } |