#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<long long> vll;
const ll LINF = 1e18;
const int INF = 1e9;
ll solve(int h, int w, const vi &d, int prev_used) {
if (h == 0 || w == 0) {
return 0;
}
int el_to_use = prev_used - 1;
while (el_to_use > 0 && (d[el_to_use] > h || d[el_to_use] > w)) {
--el_to_use;
}
int d_used = d[el_to_use];
ll h_fit = h / d_used;
ll w_fit = w / d_used;
assert(h_fit && w_fit);
return h_fit * w_fit
+ solve(h_fit * d_used, w - w_fit * d_used, d, el_to_use)
+ solve(h - h_fit * d_used, w_fit * d_used, d, el_to_use)
+ solve(h - h_fit * d_used, w - w_fit * d_used, d, el_to_use);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int h, w, n;
cin >> h >> w >> n;
vi d(n);
for (int i = 0; i < n; ++i) {
cin >> d[i];
}
sort(d.begin(), d.end());
if (h % d[0] != 0 || w % d[0] != 0) {
cout << "-1" << endl;
} else {
cout << solve(h, w, d, n) << endl;
}
return 0;
}
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 | #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned int ui; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<long long> vll; const ll LINF = 1e18; const int INF = 1e9; ll solve(int h, int w, const vi &d, int prev_used) { if (h == 0 || w == 0) { return 0; } int el_to_use = prev_used - 1; while (el_to_use > 0 && (d[el_to_use] > h || d[el_to_use] > w)) { --el_to_use; } int d_used = d[el_to_use]; ll h_fit = h / d_used; ll w_fit = w / d_used; assert(h_fit && w_fit); return h_fit * w_fit + solve(h_fit * d_used, w - w_fit * d_used, d, el_to_use) + solve(h - h_fit * d_used, w_fit * d_used, d, el_to_use) + solve(h - h_fit * d_used, w - w_fit * d_used, d, el_to_use); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int h, w, n; cin >> h >> w >> n; vi d(n); for (int i = 0; i < n; ++i) { cin >> d[i]; } sort(d.begin(), d.end()); if (h % d[0] != 0 || w % d[0] != 0) { cout << "-1" << endl; } else { cout << solve(h, w, d, n) << endl; } return 0; } |
English