#include<bits/stdc++.h> using namespace std; typedef long long ll; #define ssize(a) ((int)(a.size())) map<pair<ll, ll>, ll>mapsko; vector<ll>a; ll oblicz(ll w, ll h) { if(w > h) swap(w, h); if(w == 0) return 0; ll x = mapsko[{w,h}]; if(x) return x; ll najwpas = a.size() - 1; for(ll i = a.size() - 1; i >= 0; --i) { if(a[i] <= w) { najwpas = i; break; } } ll p = h, ile = 0; for(ll i = najwpas; i >= 0; --i) { ile += (p / a[i]) * (a[najwpas] / a[i]); p %= a[i]; } x = oblicz(w % a[najwpas], h) + w / a[najwpas] * ile; p = w; ile = 0; for(ll i = najwpas; i >= 0; --i) { ile += (p / a[i]) * (a[najwpas] / a[i]); p %= a[i]; } x = min(x, oblicz(h % a[najwpas], w) + h / a[najwpas] * ile); mapsko[{w, h}] = x; return x; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll h, w; cin >> h >> w; ll n; cin >> n; a.resize(n); for(ll i = 0 ; i < n; ++i) cin>>a[i]; if(h % a[0] != 0 || w % a[0] != 0) { cout << -1; return 0; } cout << oblicz(w, h); 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 55 56 57 58 59 60 61 62 63 64 65 66 | #include<bits/stdc++.h> using namespace std; typedef long long ll; #define ssize(a) ((int)(a.size())) map<pair<ll, ll>, ll>mapsko; vector<ll>a; ll oblicz(ll w, ll h) { if(w > h) swap(w, h); if(w == 0) return 0; ll x = mapsko[{w,h}]; if(x) return x; ll najwpas = a.size() - 1; for(ll i = a.size() - 1; i >= 0; --i) { if(a[i] <= w) { najwpas = i; break; } } ll p = h, ile = 0; for(ll i = najwpas; i >= 0; --i) { ile += (p / a[i]) * (a[najwpas] / a[i]); p %= a[i]; } x = oblicz(w % a[najwpas], h) + w / a[najwpas] * ile; p = w; ile = 0; for(ll i = najwpas; i >= 0; --i) { ile += (p / a[i]) * (a[najwpas] / a[i]); p %= a[i]; } x = min(x, oblicz(h % a[najwpas], w) + h / a[najwpas] * ile); mapsko[{w, h}] = x; return x; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll h, w; cin >> h >> w; ll n; cin >> n; a.resize(n); for(ll i = 0 ; i < n; ++i) cin>>a[i]; if(h % a[0] != 0 || w % a[0] != 0) { cout << -1; return 0; } cout << oblicz(w, h); return 0; } |