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
#include<bits/stdc++.h>

using namespace std;

int n;
long long d[40];

int last;

long long func(long long h, long long w) {
    if(h == 0 || w == 0)
        return 0;
    
    while(h < d[last] || w < d[last]) last--;
    
    long long h2 = h;
    long long w2 = w;
    long long temp1 = 0;
    long long temp2 = 0;
    for (int i=last; i>=0; i--) {
            temp1 += (h2/d[i])*(d[last]/d[i]);
            h2 = h2%d[i];
    }
    for (int i=last; i>=0; i--) {
            temp2 += (w2/d[i])*(d[last]/d[i]);
            w2 = w2%d[i];
    }
    
    //cout<<h<<" "<<w<<endl;
    
    if(temp1 < temp2) {
        return temp1*(w/d[last]) + func(h, w%d[last]);
    }
    else {
        return temp2*(h/d[last]) + func(h%d[last], w);
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    int h,w;
    cin>>h>>w>>n;
    for(int i=0;i<n;i++) cin>>d[i];
    last = n-1;
    
    if(h % d[0] == 0 && w % d[0] == 0) cout<<func(h,w)<<endl;
    else cout<<-1<<endl;
    
    return 0;
}