#include <bits/stdc++.h> using namespace std; map<pair<int, int>, long long> mem; long long solve(int n, int m, vector<int>& divs) { if (n > m) swap(n,m); if (n == 0) return 0; if (mem.count({n,m})) return mem[{n,m}]; for (auto div : divs) { if (div <= n && div <= m) { long long me = (n/div) * (m/div); int rn = n%div; int rm = m%div; long long order1 = solve(rn,m,divs) + solve(rm, n-rn, divs); long long order2 = solve(rm,n,divs) + solve(rn, m-rm, divs); mem[{n,m}] = me + min(order1, order2); return mem[{n,m}]; } } return -1; } int main() { int n,m,d; scanf(" %d %d %d", &n, &m, &d); vector<int> divs(d); for (auto &x : divs) { scanf(" %d", &x); } if (n % divs[0] != 0 || m % divs[0] != 0) { puts("-1"); return 0; } reverse(divs.begin(), divs.end()); printf("%lld\n", solve(n, m, divs)); }
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 | #include <bits/stdc++.h> using namespace std; map<pair<int, int>, long long> mem; long long solve(int n, int m, vector<int>& divs) { if (n > m) swap(n,m); if (n == 0) return 0; if (mem.count({n,m})) return mem[{n,m}]; for (auto div : divs) { if (div <= n && div <= m) { long long me = (n/div) * (m/div); int rn = n%div; int rm = m%div; long long order1 = solve(rn,m,divs) + solve(rm, n-rn, divs); long long order2 = solve(rm,n,divs) + solve(rn, m-rm, divs); mem[{n,m}] = me + min(order1, order2); return mem[{n,m}]; } } return -1; } int main() { int n,m,d; scanf(" %d %d %d", &n, &m, &d); vector<int> divs(d); for (auto &x : divs) { scanf(" %d", &x); } if (n % divs[0] != 0 || m % divs[0] != 0) { puts("-1"); return 0; } reverse(divs.begin(), divs.end()); printf("%lld\n", solve(n, m, divs)); } |